我要获取多线程程序的返回值,我们有它的队列,
代码:
#!/usr/bin/python3.6
from queue import Queue
from threading import Thread
class Worker(Thread):
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.start()
def run(self):
while True:
func, args, kargs = self.tasks.get(True, None)
if not func:
break
try:
func(*args, **kargs)
except Exception as e:
# print e
pass
self.tasks.task_done()
class ThreadPool:
def __init__(self, num_threads):
self.threads = []
self.num_threads = num_threads
self.tasks = Queue(self.num_threads)
for _ in range(self.num_threads):
worker = Worker(self.tasks)
self.threads.append(worker)
def add_task(self, func, *args, **kargs):
self.tasks.put((func, args, kargs))
def wait_completion(self):
self.tasks.join()
for _ in range(self.num_threads):
self.add_task(None, None, None)
for t in self.threads:
t.join()
def hello(i):
print("OK %s " % i)
if i == 20:
return i
else:
return i
pool = ThreadPool(int(3))
for item in range(1, 10000):
pool.add_task(hello, item)
pool.wait_completion()
我使用线程1返回值1和线程2返回值2,那么如何获取从多线程返回的值'数字'?