在 Python 中連線執行緒
Manav Narula
2022年5月17日
Python
Python Thread

多執行緒使我們能夠獲得完整的 CPU 優化。
執行緒不需要過多的記憶體開銷,多個執行緒也可以進行通訊和共享資訊。在 Python 中,我們使用 threading
模組來處理執行緒。
我們現在將討論 join()
方法與 Python 中的執行緒。我們使用這個函式來阻塞呼叫執行緒,直到它上面的執行緒被終止。
它可以正常終止或由於某些異常和超時。如果需要,也可以在 join()
函式中提及超時值。
現在讓我們用一個例子來討論這個問題。
import threading
import time
class sample(threading.Thread):
def __init__(self, time):
super(sample, self).__init__()
self.time = time
self.start()
def run(self):
print(self.time, " starts")
for i in range(0, self.time):
time.sleep(1)
print(self.time, "has finished")
t3 = sample(3)
t2 = sample(2)
t1 = sample(1)
t3.join()
print("t3.join() has finished")
t2.join()
print("t2.join() has finished")
t1.join()
print("t1.join() has finished")
輸出:
3 starts
2 starts
1 starts
1 has finished
2 has finished
3 has finished
t3.join() has finished
t2.join() has finished
t1.join() has finished
在上面的示例中,請注意其他兩個執行緒在 t3
完成時結束。然而,join()
函式持有主執行緒,其他執行緒等待它終止。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Manav Narula
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedIn