在参数列表上线程化

Threading on a list of arguments

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

例如:

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

快速修复

在您的每个 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

# create list [0, 1, ..., 9] as argument list
list_args = range(10)

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

if __name__ == '__main__':
    threads = []

    # create threads
    for arg in list_args:
        threads.append(threading.Thread(target=countdown, args=(arg,)))

    # start threads
    for thread in threads:
        print("start")
        thread.start()

    # join threads (let main thread wait until all other threads ended)
    for thread in threads:
        thread.join()

    print("finished!")