2017-09-08 35 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