2017-09-08 39 views
-1

我一直在嘗試使用列表來存儲每個線程的所有返回值。線程函數返回一個包含三個連續數字的列表。 rt_list必須是列表的列表,其中每個項目是每個線程的輸出列表。在Python中使用列表的線程

from threading import Thread 


def thread_func(rt_dict, number = None): 
    if not(number): 
     print("Number not defined.Please check the program invocation. The program will exit.")   
     sys.exit() 
    else: 

     rt_dict[number] = [number,number+1, number+2] 
    return 



numbers = [1,2,3,4,5,6] 
rt_list = [] 
thread_list = [Thread(target=thread_func, args=(rt_list),kwargs={'number':num})for num in numbers] 
for thread in thread_list: 
    thread.start() 
for thread in thread_list: 
    thread.join() 
print(rt_list) 

這是錯誤我得到當我試圖運行上述程序

Exception in thread Thread-6: 
Traceback (most recent call last): 
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner 
    self.run() 
File "/usr/lib/python3.5/threading.py", line 862, in run 
    self._target(*self._args, **self._kwargs) 
TypeError: thread_func() missing 1 required positional argument: 'rt_dict' 
+0

你通過一個列表或字典嗎? –

+1

你可以嘗試'線程(target = thread_func,kwargs = {'number':num,'rtdict':rtlist})'(無位置,只是關鍵字)。但是仍然有列表/字典問題 –

回答

1

args=(rt_list)沒有作爲一個元組實際傳遞,即使你有()。你需要通過args=(rt_list,)使它成爲一個元組,Thread的構造函數期望。

但是,目前還不清楚是什麼你正在嘗試做的,因爲你創建一個列表,並把它傳遞給Thread的構造,但thread_func的ARG被稱爲rt_dict,並訪問它像一個dict。你想要列表或列表字典嗎?

在任何情況下,您可能都需要一個線程安全的數據結構來寫入。請參閱here就是一個很好的例子。

+0

是rt_list的初始化是否正確? – al27

+0

我在答覆中增加了更多內容,請參閱上文。 – thaavik