我仍在學習如何使用多執行緒,我對該join()方法的作業原理感到困惑。根據我閱讀的內容,該join()方法會停止一切,直到執行緒終止。但看看這段代碼:
from threading import Thread
def do_something(i):
print("Sleeping...")
time.sleep(i)
print(f"Done sleeping {i}")
start = time.perf_counter()
t1, t2 = Thread(target=do_something, args=(1,)), Thread(target=do_something, args=(10,))
t1.start()
t2.start()
t2.join()
print("t2 joined")
t1.join()
print("t1 joined")
當我們運行它時,它給了我們以下輸出:
Sleeping...
Sleeping...
Done sleeping 1
Done sleeping 10
t2 joined
t1 joined
如您所見,我t2.join()在啟動兩個執行緒后立即使用,但首先列印的是Done sleeping 1. 但根據我的想法join(),我預計t1會被阻止,程式給了我們下面的輸出:
Sleeping...
Sleeping...
Done sleeping 10
Done sleeping 1
t2 joined
t1 joined
有人可以向我解釋我做錯了什么嗎?
uj5u.com熱心網友回復:
它等待執行緒完成。這就是它所做的一切。不多也不少。
uj5u.com熱心網友回復:
與同時運行多個獨立程式一樣,同時運行多個執行緒也有類似的特點,但也有一些額外的好處,具體如下:
多個執行緒與行程中的主執行緒共享相同的資料空間。因此,與行程不同,它們可以輕松共享資訊或相互通信。
也稱為輕量級行程,它們需要較少的記憶體開銷,因此比行程便宜。
多執行緒定義為同時或同時執行多個執行緒的能力。因此,一個行程中可以存在多個執行緒,其中:
加入執行緒的方法
在呼叫 join() 方法時,呼叫執行緒被阻塞,直到執行緒物件(在其上呼叫執行緒)被終止。執行緒物件可以在以下任何一種情況下終止
通過一個處理不當的例外。直到可選超時發生或正常
例子:
from threading import Thread
from threading import Event
import time
class Connection(Thread):
StopEvent = 0
def __init__(self,args):
Thread.__init__(self)
self.StopEvent = args
# The run method is overridden to define
# the thread body
def run(self):
for i in range(1,10):
if(self.StopEvent.wait(0)):
print ("Asked to stop")
break;
print("The Child Thread sleep count is %d"%(i))
time.sleep(3)
print ("A Child Thread is exiting")
Stop = Event()
Connection = Connection(Stop)
Connection.start()
print("Main thread is starting to wait for 5 seconds")
Connection.join(5)
print("Main thread says : I cant't wait for more than 5 \
seconds for the child thread;\n Will ask child thread to stop")
# ask(signal) the child thread to stop
Stop.set()
# wait for the child thread to stop
Connection.join()
print("Main thread says : Now I do something else to compensate\
the child thread task and exit")
print("Main thread is exiting")
uj5u.com熱心網友回復:
當您加入執行緒時,這意味著每個執行緒在終止之前等待另一個執行緒完成。
如果你寫
t2.join()
t1.join()
這意味著 t2 和 t1 在終止之前將等待對方完成(本質上是“殺死”執行緒)
本質上,它與我們所說的守護執行緒有關。最初,在python中,一旦一個執行緒完成了它的作業,如果它之后無事可做,它將終止整個程式。
避免這種情況的方法是在每個執行緒上呼叫 .join() ,這意味著他們將等待每個執行緒完成后再繼續(并可能完成程式)
現在,默認情況下執行緒不再是守護行程(您仍然可以使用關鍵字引數將它們設為守護行程)。
所以默認情況下,一旦一個執行緒完成它的任務,它會等待每個執行緒完成后再停止。
uj5u.com熱心網友回復:
t.join()方法將阻塞呼叫執行緒,直到執行緒t完成。我不知道如何join()實作,但可能它使用semaphore機制。請也看看這個。下面的myJoin()方法將做同樣的作業,就像類join()的方法Thread一樣。下面的程式只是簡單的例子來了解背景
from threading import Thread,Event
from time import sleep
class MyThread(Thread):
def __init__(self):
Thread.__init__(self)
self.event=Event()
def run(self):
try:
for i in range(5):
print(i)
sleep(1)
finally:
self.event.set()
def myJoin(self,timeout=None):
self.event.wait(timeout=timeout)
t = MyThread()
t.start()
print("waiting for thread t to finish")
t.myJoin()
print("thread t finished")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/510818.html
標籤:Python多线程加入
