Reputation: 21
I am trying to pass arguments to a function from a list using threads in python (Note:The values to the function should not be hard-coded and all the elements of the list will be passed.) Please look at the sample code here:
from threading import Thread
list=['john','doe','srav','dev','app']
def m1(name,prefix):
for ele in range(2):
print(name +prefix)
def main1():
t1=Thread(target=m1,args=('abcd','john'))
t2 = Thread(target=m1, args=('abcd', 'doe'))
t1.start()
t2.start()
if __name__ == '__main__':
main1()
Here i hard-coded the values to the function ('john','doe')instead of that pass from the list and all the elements will be passed.
Upvotes: 2
Views: 1387
Reputation: 114518
Your tasks are well suited for use with the concurrent.futures
module. In particular, Executor.map
applies a function to the elements of an iterable.
You can use something similar to the ThreadPoolExecutor
example in the docs:
from concurrent.futures import ThreadPoolExecutor
from itertools import repeat
names = ['john', 'doe', 'srav', 'dev', 'app']
def m1(name, prefix):
for _ in range(2):
print(name + prefix)
with ThreadPoolExecutor(2) as executor:
executor.map(m1, repeat('abcd', len(names)), names)
If you find the repeat
syntax to be awkward, you have a couple of alternatives:
with ThreadPoolExecutor(2) as executor:
for name in names:
executor.submit(m1, 'abcd', name)
OR
with ThreadPoolExecutor(2) as executor:
executor.map(lambda name: m1('abcd', name), names)
In all cases, the with
block will implicitly call executor.shutdown
, which will wait for all the tasks to complete.
As a rule, don't call a variable list
: it will shadow the name of the builtin class.
Upvotes: 3
Reputation: 1973
I am not sure if I completely understand what you are looking to achieve. My understanding is that you want to start a separate thread for each value in your list, so each value gets processed "in parallel". I modified your main1
function to do so:
def main1():
threads = [Thread(target=m1,args=('abcd',x)) for x in list]
for thread in threads: thread.start()
for thread in threads: thread.join()
threads = [Thread(target=m1,args=('abcd',x)) for x in list]
creates a separate thread for each value in the list.
for thread in threads: thread.start()
starts each thread.
for thread in threads: thread.join()
makes sure each thread is finished before returning from the main1
function (if you would rathee return immediately, just delete this line).
Upvotes: 1