Python multiple methods to get multi-threaded return value

【Summary】

        Recently, multi-threading is needed for work, and the return value of multi-threading must be obtained. Python multi-threading generally uses the threading module, but there is a problem with the threading module, which cannot return the results of running in the thread. I will explain it through three methods How to get the return value of multithreading.

1. There are three common ways to get the return value of multi-threading as follows:

Method 1: By customizing the thread class, inheriting the Thread class, and overriding the run method, writing the method of executing the function in the run method, and assigning the return value to result; and then obtaining the return value of each process by calling get_result, the code as follows:

  1. import threading  
  2. Import  Queue  
  3.   
  4.   
  5. Check if the value is even  
  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)   #Assign  the result to result while executing the function ,  
  21.         #Then  get the returned result through the get_result function  
  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()   #Must  execute join, wait for the execution of the child process to end, and then execute the main process  
  37.     result.append(t.get_result())  
  38. print result  

Method 2: Receive the return value of the subprocess through the python built-in queue Queue, and then take it out, the code is as follows:

  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()   #Wait  for the end of the child thread, and then execute it later  
  20.     for _ in range(10):  
  21.         results.append(q.get())  
  22.     print(results)  
  23.   
  24. multithreading()  

 

Method 3: Obtain the return value by creating a thread pool (threadpool). Since this module belongs to a third-party module, it needs to be installed first: pip install threadpool. The specific execution code is as follows:

  1. import threadpool  
  2.   
  3. Check if the value is even  
  4. def is_even(value):  
  5.     if value % 2 == 0:  
  6.         return True  
  7.     else:  
  8.         return False  
  9.   
  10.   
  11. #Callback  function, the accepted parameters (the request itself, and the execution result of the request work function) can be omitted  
  12. results = []  
  13. def get_result(request, result):  
  14.      global results  
  15.      results.append(result)  
  16.   
  17.   
  18. # data  is set to a list with a length of 10 , (each number in the list is passed as a parameter to the working function to run once)  
  19. data = range(10)  
  20. Declare a pool that can accommodate five threads  
  21. pool = threadpool.ThreadPool(5)  
  22. #Create  a thread running content request list (thread work function, thread work parameter list, callback function)  
  23. requests = threadpool.makeRequests(is_even, data, get_result)  
  24. Throw each thread request into the thread pool  
  25. [pool.putRequest(req) for req in requests]  
  26. #Wait  for the data to be consumed and all threads to finish running.  
  27. pool.wait()  
  28. print results  

Running the above example, the returned results are as follows:

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

 

2. Summary

      The above are the three methods for obtaining multi-threaded return values, among which method 1 and method 2 are used more often, and the first method is more flexible.

   

Guess you like

Origin blog.csdn.net/qq_20663229/article/details/94484526