锁是解决临界区资源的问题,保证每一个线程访问临界资源的时候有全部的权利
一旦某个线程获得锁, 其它试图获取锁的线程将被阻塞
acquire(blocking=True,timeout=-1) 加锁。默认True阻塞,阻塞可以设置超时时间。非阻塞时成功获取锁返回True,否则返回False。
当blocking设置为False时,不阻塞,同一个锁对象,其它线程可以重用,但最后都必须释放。
如果设置为True(默认True),其它试图调用锁的线程将阻塞,并立即返回False。阻塞可以设置超时时间
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('完成作业的总数为: {}'.format(len(worker_list)))
网友评论