您的位置:首页 > 编程语言 > Python开发

python使用互斥锁同步线程

2017-11-16 21:22 330 查看
#!/usr/bin/env python
import threading
import time
class MyThread(threading.Thread):
def run(self):
global num
time.sleep(1)
num=num+1
msg=self.name+'set num to'+str(num)
print msg
num=0
def test():
for i in range(5):
t=MyThread()
t.start()
if __name__=='__main__':
test()
~

线程同步能够保证多个线程安全访问竞争资源,最简单的同步机制是引入互斥锁。互斥锁为资源引入一个状态:锁定/非锁定。某个线程要更改共享数据时,先将其锁定,此时资源的状态为“锁定”,其他线程不能更改;直到该线程释放资源,将资源的状态变成“非锁定”,其他的线程才能再次锁定该资源。互斥锁保证了每次只有一个线程进行写入操作,从而保证了多线程情况下数据的正确性。

#创建锁

mutex = threading.Lock()

#锁定

mutex.acquire([timeout])

#释放

mutex.release()

#!/usr/bin/env python
import threading
import time
class MyThread(threading.Thread):
def run(self):
global num
time.sleep(1)
if mutex.acquire(1):
num=num+1
msg=self.name+'set num to'+str(num)
print msg
mutex.release()
num=0
mutex=threading.Lock()
def test():
for i in range(5):
t=MyThread()
t.start()
if __name__=='__main__':
test()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: