this is my code:
import threading
def worker(num):
"""thread worker function"""
print '{Worker: %s}' % num
return
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
print(threads)
and this is the result from above code:
{Worker: 0}
{Worker: 1}
{Worker: 2}
{Worker: 3}
{Worker: 4}
[<Thread(Thread-1, stopped 17204)>, <Thread(Thread-2, stopped 852)>, <Thread(Thread-3, stopped 17092)>, <Thread(Thread-4, stopped 10632)>, <Thread(Thread-5, stopped 2396)>]
how can i append those results to list and create a list something like this:
[[{Worker: 0}],[{Worker: 1}],[{Worker: 2}],[{Worker: 3}],[{Worker: 4}]]
edited: in reality my def contain a request REST method and it consume some seconds and after some trying i found thread not wait to get result and not fill array list, then i reform my code into a string variable to simulate for you, in this situation i put a time.sleep(1) in first line of def and then run thread, it's have a empty list.... i less sleep time to 0.001 till get result and thread work and array have populated.
import threading
def worker(txt):
"""thread worker function"""
if txt != '[{}]':
time.sleep(0.01) # this time has empty result till replace with 0.001 or lesser
lst.append(['{Worker: %s}' % txt])
# time.sleep(5)
return
xx = ['abc','def','ghi','jkl','mno','pqr','stw','xyz']
threads, lst = [], []
for i in xx:
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
# t.join()
print(lst) #[['{Worker: abc}'], ['{Worker: jkl}'], ['{Worker: ghi}'], ['{Worker: def}']] for 0.001 sleep time
# print(threads)
Do you mean something like this?
import threading
def worker(num):
"""thread worker function"""
lst.append(['{Worker: %s}' % num])
return
threads, lst = [], []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
print(lst)
#print(threads)
# [['{Worker: 0}'], ['{Worker: 1}'], ['{Worker: 2}'], ['{Worker: 3}'], ['{Worker: 4}']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With