我運行下面的代碼:Time.sleep似乎阻止主線程,而不僅僅是子線程?
from threading import Thread
from time import sleep
def file_write(file_input, num_lines):
sleep(10)
file = open("testfile.txt", "w")
for line in num_lines:
file.write("{}: {}".format(line, file_input))
file.close()
if __name__ == '__main__':
curr_thread = Thread(target=file_write, args=("Norah", range(5)))
curr_thread.daemon = False
curr_thread.start()
的期望是主線程將立即退出,因爲我不叫加入。但事實並非如此。睡眠呼叫是否阻止主線程?
編輯:有在這個線程中提問的類似問題:time.sleep -- sleeps thread or process?但它是不一樣的。
我看了一下線程:它表示睡眠不會導致子進程阻塞對方,但它不會說主線程會發生什麼情況。當我從接受的答案中運行代碼時,主線程並沒有立即退出,就像我想的那樣。
更新:看起來像多線程不會解決我的問題:目標是在後臺運行一堆任務。我現在正在使用子流程模塊。
可能重複的[time.sleep - 睡眠線程或進程?](https://stackoverflow.com/questions/92928/time-sleep-sleeps-thread-or-process) –
我看着線程:它說睡眠不會導致子進程阻塞對方,但它並不會說主線程會發生什麼情況。當我從接受的答案中運行代碼時,主線程並沒有立即退出,就像我想的那樣。 –
你在做'curr_thread.join()'嗎?主線程應該立即退出。加入線程將等到線程完成後退出。 –