2015-07-02 38 views
2

我想傳遞值的列表,讓每個人通過了作爲一個獨立的線程列表上:線程的參數

例如:

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

回答

1

快速修復

致電.join()對您的每個t1t2等線程結束。

詳細

我懷疑你的真正的問題是「爲什麼不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() 
+0

謝謝你的意見,因爲我是不確定的調用線程在一個循環中我把它在最近的近似的能力。 –

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

我認爲這會做你描述:

for a in list_args: 
    threading.Thread(target=countdown, args=(a,)).start() 
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!") 
+0

很好的答案,但它不是與該列表定義一起工作的代碼。 – rjonnal

+0

是的,這是正確的,我剛剛離開它,因爲它是在問題。我會將其改爲昨天用於測試的線路。 – Felix