lock(1次放1个):
import threading import time v = [] lock = threading.Lock() def func(arg): v.append(arg) time.sleep(0.01) m = v[-1] print(arg,m) for i in range(10): t =threading.Thread(target=func,args=(i,)) t.start() 结果: 01 9 9 3 9 24 9 9 7 5 9 6 99 8 9 9 9
import threading import time v = [] lock = threading.Lock() def func(arg): lock.acquire() v.append(arg) time.sleep(0.01) m = v[-1] print(arg,m) lock.release() for i in range(10): t =threading.Thread(target=func,args=(i,)) t.start()
lock只能加一把锁,加多把锁就会产生死锁.
Rlock(1次放1个):
import threading import time v = [] lock = threading.RLock() def func(arg): lock.acquire() lock.acquire() v.append(arg) time.sleep(0.01) m = v[-1] print(arg,m) lock.release() lock.release() for i in range(10): t =threading.Thread(target=func,args=(i,)) t.start() 结果: 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9
Rlock可以加多把锁.
BoundedSemaphore(1次放N个)信号量(N:指定数量个):
import time import threading lock = threading.BoundedSemaphore(3) def func(arg): lock.acquire() print(arg) time.sleep(1) lock.release() for i in range(20): t =threading.Thread(target=func,args=(i,)) t.start() 结果: 0 1 2 3 5 4 6 7 8 9 1011 12 13 14 15 1716 18 19
Condition(1次放x个)(x:不固定数量个):
import time import threading lock = threading.Condition() def func(arg): print('线程进来了') lock.acquire() lock.wait() # 加锁 print(arg) time.sleep(1) lock.release() for i in range(10): t =threading.Thread(target=func,args=(i,)) t.start() while True: inp = int(input('>>>')) lock.acquire() lock.notify(inp) lock.release()
import time import threading lock = threading.Condition() def xxxx(): print('来执行函数了') input(">>>") ct = threading.current_thread() # 获取当前线程 ct.getName() return True def func(arg): print('线程进来了') lock.wait_for(xxxx) print(arg) time.sleep(1) for i in range(10): t =threading.Thread(target=func,args=(i,)) t.start()
Event(1次放所有):
import time import threading lock = threading.Event() def func(arg): print('线程来了') lock.wait() # 加锁:红灯 print(arg) for i in range(10): t =threading.Thread(target=func,args=(i,)) t.start() input(">>>>") lock.set() # 绿灯 lock.clear() # 再次变红灯 for i in range(10): t =threading.Thread(target=func,args=(i,)) t.start() input(">>>>") lock.set()