-1

i have been trying to use a list to store all the return values from each thread. The thread function returns a list of three consecutive numbers. rt_list must be a list of lists where each item is the output list from each thread.

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) 

this is the error i get when i try to run the above program

 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'

1 Answers1

1

args=(rt_list) isn't actually passed as a tuple, even though you have the (). you need to pass args=(rt_list,) to make it a tuple, which the constructor of Thread expects.

However, it is unclear what you are trying to do, because you create a list and pass it to the Thread's constructor, but the arg of thread_func is called rt_dict, and you access it like a dict. Do you want a list of lists or a dict of lists?

In any case, you probably want a thread-safe data structure to write to. See here for a good example of that.

thaavik
  • 3,257
  • 2
  • 18
  • 25