1
我有這樣的例子代碼來解釋我的問題:如何在運行前啓動兩個線程並鎖定它們,並且只有在解鎖時才執行?
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()
我遇到一些問題如下:
我想有兩個線程(線程1和線程),它們在推出開始該程序的,但它們應該等到main()
counter
達到5或10
當main()
counter
達到5或10,但應信號/觸發/解鎖的螺紋,兩者threads
應只運行一次,然後等到新的unlock
。
我期待的代碼具有以下輸出(每行是1秒運行):
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
相反,我有不同的行爲,例如與起始:
write done by t1
write done by t1
write done by t1
write done by t1
(等)
並經過5秒
write done by t2
很多次...
有人可以幫我解釋什麼是錯的,我該如何改善這一點?
真棒!謝謝你的解釋!! – waas1919