线程参数列表

时间:2015-07-02 20:26:34

标签: python multithreading argument-passing

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

例如:

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

4 个答案:

答案 0 :(得分:1)

快速修复

在最后的每个.join()t1等主题上致电t2

详细

我怀疑你真正的问题是'为什么不countdown被召唤? Thread.join()方法导致主线程在继续之前等待其他线程完成执行。没有它,一旦主线程完成,它就会终止整个过程。

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

其他问题:

  1. 最好包含minimum working example。您的代码无法按照书面形式执行。

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

  3. 您无需两次导入time

  4. 这可能接近你想要的:

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我认为这会做你所描述的:

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

答案 3 :(得分:0)

您可以将所有线程添加到列表中,使其与参数数量无关。在主程序结束时,您必须加入所有线程。否则主线程退出并终止所有其他线程。

工作代码:

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!")