我是多執行緒的新手,并且一直試圖在后臺為我的一個程式制作一個計時器,而其他幾個執行緒則執行他們的代碼。我目前的代碼設定如下:
def timer(length):
global kill
kill = False
print('Timer starting!')
for i in range(length):
time.sleep(1)
kill = True
def r(interval, id):
print(id, "running")
while True:
if kill:
break
time.sleep(interval)
print(f'{id}: {time.localtime()}')
timerThread = threading.Thread(target = timer(15))
runThread1 = threading.Thread(target = r(2, "thread1"))
runThread2 = threading.Thread(target = r(5, "thread2"))
threads = [timerThread, runThread1, runThread2]
timerThread.start()
runThread1.start()
runThread2.start()
for t in threads:
t.join()
顯然,它不是一個有用的程式(只是為了幫助我學習執行緒模塊的基礎知識),但我仍然需要知道如何解決這個問題。我 95% 確定問題是由在計時器函式中使用“time.sleep(1)”引起的,但我不知道使用只會影響一個執行緒的替代方法。我會很感激任何建議。
uj5u.com熱心網友回復:
您甚至在創建執行緒之前就呼叫了函式:
timerThread = threading.Thread(target = timer(15))
runThread1 = threading.Thread(target = r(2, "thread1"))
runThread2 = threading.Thread(target = r(5, "thread2"))
您需要傳遞一個可呼叫物件target,而不是已經呼叫它的結果;可以args單獨傳遞:
timerThread = threading.Thread(target=timer, args=(15,))
runThread1 = threading.Thread(target=r, args=(2, "thread1"))
runThread2 = threading.Thread(target=r, args=(5, "thread2"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/450264.html
