當前的代碼:執行多個線程同時
def export_data(file):
<runs the db2 database command to export tables to file>
def export_to_files(yaml):
logger = logging.getLogger("export_to_files")
thread1 = threading.Thread(target=export_data, args=[out_file1])
thread1.start()
thread2 = threading.Thread(target=export_data, args=[out_file2])
thread2.start()
thread1.join()
thread2.join()
def main():
export_to_files()
if __name__ == "__main__":
main()
我的理解是,只有join()
塊調用線程。然而,我沒有意識到thread1.join()
甚至會阻止thread2
執行,實質上使得代碼僅運行1個線程,即thread1
。
如何同時執行兩個線程,同時讓主線程等待兩個線程完成?
編輯:我站在糾正,2線程運行,但它似乎只有1線程實際上是「做」的事情在某個時間點。
爲了進一步闡述,callable_method
正在從數據庫讀取數據並寫入文件。雖然我現在可以看到2個文件正在更新(每個線程寫入一個單獨的文件),但其中一個文件現在不會更新很長一段時間,而另一個文件是最新的。
有沒有正在使用的連接對象。查詢從db2命令行界面運行。
'thread1.join()'不應該阻止'thread2'執行。 –
當你調用它們的'.start()'方法時,線程開始運行。 '.join()'阻塞,直到線程_stops_。 –
你有沒有嘗試刪除join()調用?它應該按照預期執行,如果你這樣做。 – Surveon