【问题标题】:How to keep alive a thread until its function is complete in Python?如何让线程保持活动状态,直到其功能在 Python 中完成?
【发布时间】:2020-09-15 11:39:44
【问题描述】:

我是多线程的新手,在 python 中编写了一个代码,该函数从列表中弹出一个元素然后下载它,我正在使用线程下载多个文件。问题是线程在下载完全完成之前终止并且代码结束。(下载不完整的文件):

这是线程的代码(下载功能运行良好,只有线程有问题):

for i in range(0, 6):
    time.sleep(10)
    name = list.pop(0)
    _thread.start_new_thread(func_download,
                             (name, bucket_name, list, repo_name))
time.sleep(10)

【问题讨论】:

  • 展示你是如何定义你的自定义方法的,start_new_thread

标签: python multithreading file download


【解决方案1】:

如果这是现实世界的任务,请尽可能避免手动线程处理。

对于您的特定情况,ThreadPoolExecutor.map 完全符合您的需要。

如果您需要更精细的控制,请查看queues,这是更好的同步元素。

【讨论】:

    【解决方案2】:

    您的主线程必须等待其他线程完成。这并不难做到。为此,您使用 join() 方法。

    threads=[] #list to keep an eye on the threads
    
    for i in range(0, 6):
        time.sleep(10)
        name = list.pop(0)
        thread=_thread.start_new_thread(func_download,
                                 (name, bucket_name, list, repo_name))
        threads.append(thread)#add thread to the list
    
    
    for thread in threads:
         #only move on when this thread finished
         thread.join()
    #only when all threads finished you will get here
    

    现在程序应该只在所有线程完成后才能继续。

    【讨论】:

    • 感谢您的回答,当我进行更改时,我得到一个错误“模块'_thread'没有属性'join'”虽然我在代码的开头使用了“import threading”模块
    • @DarcyM 对不起。里面有错误。修复。 _thread.start_new_thread 向线程返回一个标识符,您必须将该标识符添加到列表中
    • 这与标识符无关,我们不能将 thread.join() 与 _thread 一起使用,但可以将其与“线程”一起使用
    【解决方案3】:

    我已经弄清楚需要什么:

    ```   for i in range(0, 5):
            time.sleep(5)
            name = list.pop(0)
            print("This is threading") # this print was testing purposes
            thread = threading.Thread(target=function_name,
                                      args=(name, bucket_name, list, repo_name))
            print(thread)
            print("Now starting")
            thread.start()
            print("Waiting")
            thread.join()
        time.sleep(5)```
    

    基本上要使用join(),我们将使用“threading.Thread”而不是“_thread.start_new_thread”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-22
      • 2020-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多