1, lock lock
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()
2, rlock lock
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()
3, semaphore lock
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()
4, condition locks
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 () # ############## embodiment two ########### ### "" " DEF xxxx (): Print ( 'to perform a function') the INPUT (" >>> ") # threading.current_thread CT = () # get the current thread # ct.getName () return True DEF FUNC (Arg): Print ( 'thread came') lock.wait_for (XXXX) Print (Arg) the time.sleep (. 1) for I in Range (10): T = of the threading.Thread (target = FUNC, args = (I ,)) t.start () "" "
5, event lock
Import Time Import Threading Lock = threading.Event () DEF FUNC (Arg): Print ( ' thread a ' ) lock.wait () # lock: Red Print (Arg) for I in Range (10 ): T = of the threading.Thread (target = FUNC, args = (I,)) t.start () INPUT ( " >>>> " ) lock.set () # green lock.clear () # again becomes red for I in Range (10 ): t=threading.Thread(target=func,args=(i,)) t.start() input(">>>>") lock.set()