脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python实现的多线程同步与互斥锁功能示例

Python实现的多线程同步与互斥锁功能示例

2020-12-21 00:29爱橙子的OK绷 Python

这篇文章主要介绍了Python实现的多线程同步与互斥锁功能,涉及Python多线程及锁机制相关操作技巧,需要的朋友可以参考下

本文实例讲述了Python实现的多线程同步互斥锁功能。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#! /usr/bin/env python
#coding=utf-8
import threading
import time
'''
#1、不加锁
num = 0
class MyThread(threading.Thread):
  def run(self):
    global num
    time.sleep(1) #一定要sleep!!!
    num = num + 1
    msg = self.name + ' num is ---- ' + str(num)
    print msg
def test():
  for i in range(10):
    s = MyThread() #实例化一个Thread对象,每个Thread对象代表着一个线程
    s.start() #通过start()方法,开始线程活动
'''
#'''
class MyThread(threading.Thread):
  def run(self):
    for i in range(3):
      time.sleep(1)
      msg = self.name+' @ '+str(i)
      print msg
def test():
  for i in range(5):
    t = MyThread()
    t.start()
#'''
'''
#2、加锁
num = 0 #多个线程共享操作的数据
mu = threading.Lock() #创建一个锁
class MyThread(threading.Thread):
  def run(self):
    global num
    time.sleep(1)
    if mu.acquire(True): #获取锁状态,一个线程有锁时,别的线程只能在外面等着
      num = num + 1
      msg = self.name + ' num is ---- ' + str(num)
      print msg
      mu.release() #释放锁
def test():
  for i in range(10):
    s = MyThread()
    s.start()
'''
if __name__ == '__main__':
  test()

运行结果:

Python实现的多线程同步与互斥锁功能示例

再分别运行注释中的每一部分代码:

1. 不加锁:

Python实现的多线程同步与互斥锁功能示例

2. 加锁:

Python实现的多线程同步与互斥锁功能示例

希望本文所述对大家Python程序设计有所帮助。

原文链接:http://blog.csdn.net/will130/article/details/50474672

延伸 · 阅读

精彩推荐