Skip to main content
 首页 » 编程设计

python之在参数列表上线程化

2025年05月04日10jackei

我想传递一个值列表,并将每个值作为一个独立的线程传递:

例如:

import time 
import threading 
 
list_args = [arg1, arg2, arg3, ...., argn] 
 
# Code to execute in an independent thread 
import time 
def countdown(n): 
    while n > 0: 
        print('T-minus', n) 
        n -= 1 
        time.sleep(0.5) 
 
 
# Create and launch a thread 
t1 = threading.Thread(target=countdown, args=(arg1,)) 
t2 = threading.Thread(target=countdown, args=(arg2,)) 
. 
. 
. 
tn = threading.Thread(target=countdown, args=(argn,)) 
t1.start(); t2.start(); tn.start() 

请您参考如下方法:

快速修复

在每个 t1、t2 等线程的末尾调用 .join()。

详情

我怀疑您真正的问题是“为什么不调用 countdown?” Thread.join() 方法导致主线程等待其他线程完成执行后再继续。没有它,一旦主线程完成,它就会终止整个进程。

在您的程序中,当主线程完成执行时,进程与其所有线程一起终止,然后后者才能调用它们的 countdown 函数。

其他问题:

  1. 最好包含一个 minimum working example .您的代码无法按照编写的方式执行。

  2. 通常使用某种数据结构来管理线程。这很好,因为它使代码更紧凑、通用且可重用。

  3. 您不需要两次导入 time。

这可能接近您想要的:

import time 
import threading 
 
list_args = [1,2,3] 
 
def countdown(n): 
    while n > 0: 
        print('T-minus', n) 
        n -= 1 
        time.sleep(0.5) 
 
 
# Create and launch a thread 
threads = [] 
for arg in list_args: 
    t = threading.Thread(target=countdown,args=(arg,)) 
    t.start() 
    threads.append(t) 
 
for thread in threads: 
    thread.join()