如何等到所有线程完成?

时间:2017-02-27 00:47:39

标签: python multithreading download

虽然我用Google搜索并得到了很多结果,但它们并不是我想要的。我的主要代码如下

def main:
    start = datetime.now()
    browser = webdriver.PhantomJS()
    download()
    browser.quit()
    showTime()

def download:
    for imageSecond in imageSeconds:
        urlServer = imageSecond.get("src")
        pathLocal = formatPath(downloadLocationPath, ntpath.basename(urlServer))

        if not os.path.isfile(pathLocal):
             ts.append(createNewDownloadThread(browser, urlServer, pathLocal))
        else:
            logger.info('Downloaded: {}'.format(urlServer + " -> " + pathLocal))
            showTime()

    for t in ts:
        t.join()

def showTime:
    end = datetime.now()
    runtime = end - start
    logger.info('Sta Time: {}'.format(start))
    logger.info('End Time: {}'.format(end))
    logger.info('Run Time: {}'.format(runtime))
    sys.exit(0)

我输出如下

2017-02-27 09:42:12,817 - INFO - MainThread - Downloaded: https://secure-api.userlocal.jp
2017-02-27 09:42:12,833 - INFO - MainThread - Sta Time: 2017-02-27 09:41:43.895126
2017-02-27 09:42:12,833 - INFO - MainThread - End Time: 2017-02-27 09:42:12.833492
2017-02-27 09:42:12,833 - INFO - MainThread - Run Time: 0:00:28.938366
2017-02-27 09:42:12,849 - INFO - Thread-323 - Download: https://secure-api.userlocal.jp
2017-02-27 09:42:12,849 - INFO - Thread-324 - Download: https://secure-api.userlocal.jp

但我想输出如下,我该怎么办?

2017-02-27 09:42:12,817 - INFO - MainThread - Downloaded: https://secure-api.userlocal.jp
2017-02-27 09:42:12,849 - INFO - Thread-323 - Download: https://secure-api.userlocal.jp
2017-02-27 09:42:12,849 - INFO - Thread-324 - Download: https://secure-api.userlocal.jp
2017-02-27 09:42:12,833 - INFO - MainThread - Sta Time: 2017-02-27 09:41:43.895126
2017-02-27 09:42:12,833 - INFO - MainThread - End Time: 2017-02-27 09:42:12.833492
2017-02-27 09:42:12,833 - INFO - MainThread - Run Time: 0:00:28.938366

1 个答案:

答案 0 :(得分:2)

您的示例中缺少代码,我猜您在上面的createNewDownloadThread()方法中调用newthread.start(),不是吗?

你可能知道通常的工作方式是调用thread.start()和thread.join(),所以它会阻塞直到线程完成。

我认为在for循环中执行此操作可能会更好:

Key