我的應用程式需要同時運行一個函式和一個執行緒。我在函式內創建了一個執行緒并啟動了該執行緒。我嘗試同時運行函式和執行緒,我想停止執行緒,直到函式內部滿足某些條件。但是執行緒首先運行直到它完成,然后只有函式開始執行。我無法實作并發。
這是我的代碼
import threading
from time import sleep
start_threads = False
stop_threads = True
def testthread():
global stop_threads
k = 0
while k < 100:
print("testthread -->",k)
k = 1
sleep(1)
if k == 100:
stop_threads = True
if stop_threads:
break
def testfunction():
global stop_threads
t1 = threading.Thread(target = testthread)
t1.start()
i = 0
while i < 100:
print("testfunction-->",i)
i = 1
sleep(1)
if i == 100:
stop_threads = False
if stop_threads:
t1.join()
print('thread killed')
testfunction()
我試圖得到像......的輸出
testthread --> 0
testthread --> 1
.
.
.
testthread --> 99
thread killed
testfunction--> 1
thread killed
'
'
'
testfunction--> 98
thread killed
testfunction--> 99
>>>
我期望輸出像..
>>>
testthread --> 0
testfunction --> 0
testthread --> 1
testfunction --> 1
'
'
'
testthread -->99
threadkilled
testfunctionn -->99
uj5u.com熱心網友回復:
一方面,您從stop_threadsTrue開始,因此 main 函式只是在一次迭代后將其洗掉,然后等待您開始的執行緒完成。
這不是查看同一個全域變數,您不能讓多個執行緒查看同一個全域變數并期望它是執行緒安全的。但是,如果您簡化代碼,很明顯這根本不需要:
import threading
from time import sleep
def testthread():
k = 0
while k < 3:
print("testthread -->", k)
k = 1
sleep(1)
def testfunction():
t1 = threading.Thread(target=testthread)
t1.start()
i = 0
while i < 5:
print("testfunction-->", i)
i = 1
sleep(1)
t1.join()
testfunction()
輸出:
testthread --> 0
testfunction--> 0
testfunction--> 1
testthread --> 1
testfunction--> 2
testthread --> 2
testfunction--> 3
testfunction--> 4
執行緒在呼叫 時有效地相互讓步sleep(),因此代碼按預期作業,如果您玩弄值< 3和< 5,您將看到任何一個都可以完成。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/349080.html
上一篇:無法從其他執行緒添加串列項
下一篇:執行緒之間的對話
