defconsumer(cond): t = threading.current_thread() with cond: cond.wait() # wait()方法创建了一个名为waiter的锁,并且设置锁的状态为locked。这个waiter锁用于线程间的通讯 print('{}: Resource is available to consumer'.format(t.name))
defproducer(cond): t = threading.current_thread() with cond: print('{}: Making resource available'.format(t.name)) cond.notify_all() # 释放waiter锁,唤醒消费者
threads = [] for i inrange(4): thread = threading.Thread(target=myqueue, args=(q,)) thread.start() threads.append(thread)
for thread in threads: thread.join()
6.线程池
1 2 3 4 5 6 7 8 9 10 11 12
from concurrent.futures import ThreadPoolExecutor, as_completed import time
defsquare(n): time.sleep(1) return n * n
if __name__ == '__main__': with ThreadPoolExecutor(max_workers=3) as executor: tasks = [executor.submit(square, num) for num inrange(10)] for future in as_completed(tasks): print(future.result())