处理参数列表

2024-06-12 21:28:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如:

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()

Tags: importtargettimeargsthreadstarttnt1
3条回答

快速修复

在结尾对您的t1t2等线程调用.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()

我想这会像你所描述的那样:

for a in list_args:
    threading.Thread(target=countdown, args=(a,)).start()
import time
import threading

list_args = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

# Code to execute in an independent thread
def countdown(n):
    while n > 0:
        print('T-minus', n)
        n -= 1
        time.sleep(0.5)


# Create and launch a thread
for item in list_args:
    thread = threading.Thread(target=countdown, args=(item,))
    thread.start()

相关问题 更多 >