
1、threading模块中定义了Lock类,可以实现锁
创建锁对象: mutex = threading.Lock()
上锁: mutex.acquire()
释放锁: mutex.release()
2、注意
如果这个锁之前是没有上锁的,那么acquire就不会阻塞
如果调用acquire之前这个锁是被其它线程上了锁的,那么acquire就会阻塞,直到这个锁被释放
3、实例
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 | import threading
import time
num = 0
def count_test1():
global num
for i in range(100000):
mutex.acquire()
num += 1
mutex.release()
print( "count_test1-->num:%s" %num)
def count_test2():
global num
for i in range(100000):
mutex.acquire()
num += 1
mutex.release()
print( "count_test2-->num:%s" %num)
mutex = threading.Lock()
t1 = threading.Thread(target=count_test1)
t2 = threading.Thread(target=count_test2)
t1.start()
t2.start()
t1.join()
t2.join()
print( "最终的num:%s" %num)
|
以上就是python使用互斥锁处理资源分配,希望能对大家有所帮助,更多知识尽在python学习网。