Condition 源代码精简版,代码写的乱,大概是这个意思,用2个锁实现交替运行,
from threading import Lock,Thread
class MyCondition:
def __init__(self):
self.lock = Lock()
self.waiter = Lock()
def __enter__(self):
self.lock.acquire()
def __exit__(self, exc_type, exc_val, exc_tb):
self.lock.release()
def wait(self):
self.lock.release()
self.waiter.acquire()
self.waiter.acquire()
self.lock.acquire()
def notify(self):
self.waiter.release()
self.waiter = Lock()
con = MyCondition()
def t1():
with con:
print('Thread 1 {}'.format('first'))
con.wait()
con.notify()
print('Thread 1 {}'.format('second'))
con.wait()
con.notify()
def t2():
with con:
con.notify()
print('Thread 2 {}'.format('first'))
con.wait()
con.notify()
print('Thread 2 {}'.format('second'))
con.wait()
t1 = Thread(target=t1)
t2 = Thread(target=t2)
t1.start()
t2.start()