python多线程threading.Lock锁用法实例
程序员文章站
2024-02-11 12:53:40
本文实例讲述了python多线程threading.lock锁的用法实例,分享给大家供大家参考。具体分析如下:
python的锁可以独立提取出来
复制代码 代码如下:m...
本文实例讲述了python多线程threading.lock锁的用法实例,分享给大家供大家参考。具体分析如下:
python的锁可以独立提取出来
复制代码 代码如下:
mutex = threading.lock()
#锁的使用
#创建锁
mutex = threading.lock()
#锁定
mutex.acquire([timeout])
#释放
mutex.release()
#锁的使用
#创建锁
mutex = threading.lock()
#锁定
mutex.acquire([timeout])
#释放
mutex.release()
锁定方法acquire可以有一个超时时间的可选参数timeout。如果设定了timeout,则在超时后通过返回值可以判断是否得到了锁,从而可以进行一些其他的处理。
复制代码 代码如下:
#!/usr/bin/env python
#coding=utf-8
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()
thread-1 set num to 1
thread-3 set num to 2
thread-4 set num to 3
thread-5 set num to 4
thread-2 set num to 5
#coding=utf-8
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()
thread-1 set num to 1
thread-3 set num to 2
thread-4 set num to 3
thread-5 set num to 4
thread-2 set num to 5
希望本文所述对大家的python程序设计有所帮助。