我有一個繼承自 Python 中的 Thread 的類 FrameThread
class FrameThread(Thread):
def __init__(self, threadID, customFunction, args):
threading.Thread.__init__(self)
self.threadID = threadID
self.task = customFunction
self.args = args
self.output = None
def run(self):
self.output = self.task(self.args)
我有這個類的原因是,一旦執行緒完成運行我的自定義函式(通過呼叫 is_alive() 進行檢查),我就可以檢索函式回傳值。
我的程式看起來像這樣
在第一塊代碼中
mythread = FrameThread(threadID, myCustomFunction, args)
mythread.start()
在第二個代碼塊中
if not mythread.is_alive():
outputVar = mythread.output
print(outputVar)
這有時有效,有時無效。控制臺要么列印出 myCustomFunction 的實際回傳值,要么列印出 None。所以我認為這可能是因為在 python 運行“outputVar = mythread.output”之前該值沒有傳遞給 mythread.output。所以我在第二個代碼塊中添加了一個回圈,只是為了測驗。
if not mythread.is_alive():
while mythread.output == None:
print("Reee")
outputVar = mythread.output
print(outputVar)
令我驚訝的是,程式列印出一堆“Reee”,然后列印出正確的 outputVar 值。
This behavior is very weird and it's probably because I did something wrong (very likely in my FrameThread class). Please let me know how I could probably fix it, or how to implement the FrameThread subclass properly.
uj5u.com熱心網友回復:
我檢查了threading模塊的代碼,但找不到發生這種情況的原因。join不過,如果你在得到結果之前執行緒,你可以擺脫這個問題。無論如何,您應該join在某個時候使用該執行緒。您應該將第二個代碼塊替換為:
if not mythread.is_alive():
mythread.join()
outputVar = mythread.output
print(outputVar)
像這樣使用is_alive()很少有用:它主要用于檢查 ajoin是否超時。例如:
mythread.join(0)
if mythread.is_alive():
# timed out
print('Still waiting for thread to finish...')
# do some work in the main thread...
else:
outputVar = mythread.output
print(outputVar)
我建議您考慮使用其他型別的同步或concurrent.futures
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/423036.html
標籤:
