鎖是解決臨界區(qū)資源的問題,保證每一個線程訪問臨界資源的時候有全部的權(quán)利
一旦某個線程獲得鎖赖淤, 其它試圖獲取鎖的線程將被阻塞
acquire(blocking=True,timeout=-1) 加鎖芦昔。默認(rèn)True阻塞,阻塞可以設(shè)置超時時間。非阻塞時成功獲取鎖返回True泊窘,否則返回False。
當(dāng)blocking設(shè)置為False時像寒,不阻塞烘豹,同一個鎖對象,其它線程可以重用诺祸,但最后都必須釋放携悯。
如果設(shè)置為True(默認(rèn)True),其它試圖調(diào)用鎖的線程將阻塞筷笨,并立即返回False憔鬼。阻塞可以設(shè)置超時時間
import time
import threading
from threading import Thread, Lock
worker_list = []
lock = Lock()
def students(num):
while True:
lock.acquire() # 添加線程鎖
if len(worker_list) >= num:
break
time.sleep(0.001)
worker_list.append(1)
lock.release() # 釋放線程鎖
print('current_thread is {} worker_list = {}'.format(threading.current_thread().name, len(worker_list)))
def student(num):
while True:
with lock:
if len(worker_list) >= num:
break
time.sleep(0.001)
worker_list.append(1)
print('current_thread is {} worker_list = {}'.format(threading.current_thread().name, len(worker_list)))
if __name__ == '__main__':
for i in range(10):
# Thread(target=students, name='stadent {}'.format(i), args=(1000,)).start()
Thread(target=student, name='with {}'.format(i), args=(10000,)).start()
time.sleep(3)
print('完成作業(yè)的總數(shù)為: {}'.format(len(worker_list)))