我對 python 和執行緒很陌生。我的目標是擁有一個永久運行的主執行緒和依賴于另一個的其他執行緒。我嘗試了不同的東西,.join()但我無法得到答案。
這是我想到的一張圖片: Thread Imagination
我需要守護行程之類的東西,還是可以簡單地解決這個問題.join()?
uj5u.com熱心網友回復:
試試這個結構:
from threading import Thread
from time import sleep
def do_work_1():
print("Thread 1 starting")
sleep(1)
print("Thread 1 done")
def do_work_2(parent_thread):
print("Thread 2 wait thread 1 to finish")
parent_thread.join()
print("Thread 2 starting")
sleep(1)
print("Thread 2 done")
def do_work_3(parent_thread):
print("Thread 3 wait thread 2 to finish")
parent_thread.join()
print("Thread 3 starting")
sleep(1)
print("Thread 3 done")
thread1 = Thread(target=do_work_1)
thread2 = Thread(target=do_work_2, args=(thread1,)) # Do not miss the comma!
thread3 = Thread(target=do_work_3, args=(thread2,))
thread1.start()
thread2.start()
thread3.start()
for num in range(6):
print("Main thread still do job", num)
sleep(0.60)
thread3.join()
print("Job done")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/491151.html
