Python多种方法获取多线程返回值

【摘要】

        近段时间,工作上需要用到多线程,并且要获取多线程的返回值,python多线程一般使用threading模块,但threading模块有个问题,无法返回线程里面运行的结果,我通过三种方法讲解如何获取多线程的返回值。

一、通过获取多线程的返回值有如下三种常用方法:

方法一:通过自定义线程类,继承Thread类,并复写run方法,在run方法中写入执行函数的方式,并把返回值赋值给result;然后通过调用get_result获取每个进程的返回值,代码如下:

  1. import threading  
  2. import Queue  
  3.   
  4.   
  5. 判断值是否为偶数  
  6. def is_even(value):  
  7.     if value % 2 == 0:  
  8.         return True  
  9.     else:  
  10.         return False  
  11.   
  12.   
  13. class MyThread(threading.Thread):  
  14.     def __init__(self, func, args=()):  
  15.         super(MyThread, self).__init__()  
  16.         self.func = func  
  17.         self.args = args  
  18.   
  19.     def run(self):  
  20.         self.result = self.func(*self.args)  在执行函数的同时,把结果赋值给result,  
  21.         然后通过get_result函数获取返回的结果  
  22.   
  23.     def get_result(self):  
  24.         try:  
  25.             return self.result  
  26.         except Exception as e:  
  27.             return None  
  28.   
  29. result = []  
  30. threads = []  
  31. for i in range(10):  
  32.     t = MyThread(is_even, args=(i,))  
  33.     t.start()  
  34.     threads.append(t)  
  35. for t in threads:  
  36.     t.join()  一定执行join,等待子进程执行结束,主进程再往下执行  
  37.     result.append(t.get_result())  
  38. print result  

方法二:通过python内置的队列Queue接收子进程的返回值,然后再从中取出,代码如下:

  1. import threading  
  2. import Queue  
  3. def is_even(value, q):  
  4.     if value % 2 == 0:  
  5.         q.put(True)  
  6.     else:  
  7.         q.put(False)  
  8.   
  9.   
  10. def multithreading():  
  11.     q = Queue.Queue()  
  12.     threads = []  
  13.     results = []  
  14.     for i in range(10):  
  15.         t = threading.Thread(target=is_even, args=(i, q))  
  16.         t.start()  
  17.         threads.append(t)  
  18.     for thread in threads:  
  19.         thread.join()  等待子线程结束后,再往后面执行  
  20.     for _ in range(10):  
  21.         results.append(q.get())  
  22.     print(results)  
  23.   
  24. multithreading()  

 

方法三:通过创建线程池(threadpool)的方式获取返回值,由于该模块属于第三方模块,因此需要先进行安装:pip install threadpool,具体执行代码如下:

  1. import threadpool  
  2.   
  3. 判断值是否为偶数  
  4. def is_even(value):  
  5.     if value % 2 == 0:  
  6.         return True  
  7.     else:  
  8.         return False  
  9.   
  10.   
  11. 回调函数,接受的参数(请求本身,和请求工作函数执行结果)可以省略  
  12. results = []  
  13. def get_result(request, result):  
  14.      global results  
  15.      results.append(result)  
  16.   
  17.   
  18. # data 设置为长度为10的列表,(列表中每一个数作为参数传递给工作函数运行一次)  
  19. data = range(10)  
  20. 声明可容纳五个线程的池  
  21. pool = threadpool.ThreadPool(5)  
  22. 创建线程运行内容请求列表(线程工作函数,线程工作参数列表,回调函数)  
  23. requests = threadpool.makeRequests(is_even, data, get_result)  
  24. 将每一个线程请求扔进线程池  
  25. [pool.putRequest(req) for req in requests]  
  26. 等待data被消耗完,所有线程运行结束。  
  27. pool.wait()  
  28. print results  

运行以上例子,返回的结果如下:

  1. C:\Python27\python.exe D:/bluekingProject/wd-test/app-publish/test.py  
  2. [True, False, True, False, True, False, True, False, True, False]  

 

二、总结

      以上就是获取多线程返回值的三种方法,其中方法一和方法二用得比较多,并且第一种方法更灵活。

   

猜你喜欢

转载自blog.csdn.net/qq_20663229/article/details/94484526