本文实例讲述了python多线程threading.Lock锁的用法实例,分享给大家供大家参考。具体分析如下:
python的锁可以独立提取出来
mutex = threading.Lock() #锁的使用 #创建锁 mutex = threading.Lock() #锁定 mutex.acquire([timeout]) #释放 mutex.release()
#!/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
希望本文所述对大家的Python程序设计有所帮助。