我有这个示例代码来解释我的问题:
import threading
import time
class thread1(threading.Thread):
def __init__(self, lock):
threading.Thread.__init__(self)
self.daemon = True
self.start()
self.lock = lock
def run(self):
while True:
self.lock.acquire(True)
print ('write done by t1')
self.lock.release()
class thread2(threading.Thread):
def __init__(self, lock):
threading.Thread.__init__(self)
self.daemon = True
self.start()
self.lock = lock
def run(self):
while True:
self.lock.acquire(True)
print ('write done by t2')
self.lock.release()
if __name__ == '__main__':
lock = threading.Lock()
t1 = thread1(lock)
t2 = thread2(lock)
lock.acquire(True)
counter = 0
while True:
print("main...")
counter = counter + 1
if(counter==5 or counter==10):
lock.release() # Here I want to unlock both threads to run just one time and then wait until I release again
time.sleep(1)
t1.join()
t2.join()
我遇到的一些问题如下:
我希望在程序开头有两个线程(thread1和thread2),但它们应该等到main()
counter
达到5或10。
当main()
counter
达到5或10时,它应该发出信号/触发/解锁线程,threads
只应运行一次,然后等到新{{1} }}
我希望代码具有以下输出(每行运行1秒):
unlock
相反,我有不同的行为,例如以:
开头main...
main...
main...
main...
main...
write done by t1
write done by t2
main...
main...
main...
main...
main...
write done by t1
write done by t2
(等)
5秒后
write done by t1
write done by t1
write done by t1
write done by t1
很多次......
有人可以帮我解释错误吗?我该如何改进?
答案 0 :(得分:1)
我建议您使用 Condition Object 而不是Lock。
以下是基于您的代码的示例。
_.isEqual