1. 程式人生 > >lock多線程鎖

lock多線程鎖

lee global print run 多線程 pre threads -a cti


import threading
import time

def run(n):
lock.acquire()
global num
num +=1

lock.release()
time.sleep(1)


lock = threading.Lock()
num = 0
t_objs = [] #存線程實例
for i in range(1000):
t = threading.Thread(target=run,args=("t-%s" %i ,))
t.start()
t_objs.append(t) #為了不阻塞後面線程的啟動,不在這裏join,先放到一個列表裏

for t in t_objs: #循環線程實例列表,等待所有線程執行完畢
t.join()

print("----------all threads has finished...",threading.current_thread(),threading.active_count())

print("num:",num)

lock多線程鎖