ReusableBarrier 模式可以保证一组线程可以全部执行到某一语句后才继续往下执行。
# -*- coding: utf-8 -*-
import threading
import time
from threading import Semaphore, Thread
class ReusableBarrierClass:
def __init__(self, thread_count):
self.thread_count = thread_count
self.count = 0
self.mutex = Semaphore(1)
self.turnstile = Semaphore(0)
self.turnstile2 = Semaphore(1)
def __enter__(self):
self.mutex.acquire()
self.count += 1
if self.count == self.thread_count:
print(u"当前线程号", threading.currentThread().getName(), u" turnstile 打开")
self.turnstile.release()
self.turnstile2.acquire()
self.mutex.release()
self.turnstile.acquire()
self.turnstile.release()
def __exit__(self, exc_type, exc_value, traceback):
self.mutex.acquire()
self.count -= 1
if self.count == 0:
print(u"当前线程号", threading.currentThread().getName(), u" turnstile 重新关闭")
self.turnstile.acquire()
self.turnstile2.release()
self.mutex.release()
self.turnstile2.acquire()
self.turnstile2.release()
barrier = ReusableBarrierClass(3)
def worker(br, idx):
print(u"当前线程号", threading.currentThread().getName(), u" 函数进入")
with br:
print(u"当前线程号", threading.currentThread().getName(), u" 正在执行")
time.sleep(idx * 2)
print(u"当前线程号", threading.currentThread().getName(), u" 执行完毕")
print(u"当前线程号", threading.currentThread().getName(), u" 函数退出执行")
for i in range(barrier.thread_count):
Thread(target=worker, args=(barrier, i)).start()