我想将文件上传到两个ftp站点。两个完成后,我需要删除该文件。 如果不阻止主函数运行,ftp和delete函数都将通过线程实现,这意味着将有3个线程同时在后台运行。由于线程化,一个简单的问题变得复杂。
以下是可能的解决方案:
两者都有效,但我不认为它们是最好的方法。谁能分享他/她的想法?
答案 0 :(得分:0)
使用信号量。
在父处理程序中创建一个0的信号量并将其移交给线程。
import threading
sem = threading.Semaphore(0)
hostThread = threading.Thread(target=uploadToHost, args=(sem,))
backupThread = threading.Thread(target=uploadToBackup, args=(sem,))
sem.acquire() # Wait for one of them to finish
sem.acquire() # Wait for the other to finish
在您的孩子中,您只需在上传完成后致电sem.release
。