【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:
- import threading
- Import Queue
- # Check if the value is even
- def is_even(value):
- if value % 2 == 0:
- return True
- else:
- return False
- class MyThread(threading.Thread):
- def __init__(self, func, args=()):
- super(MyThread, self).__init__()
- self.func = func
- self.args = args
- def run(self):
- self.result = self.func(*self.args) #Assign the result to result while executing the function ,
- #Then get the returned result through the get_result function
- def get_result(self):
- try:
- return self.result
- except Exception as e:
- return None
- result = []
- threads = []
- for i in range(10):
- t = MyThread(is_even, args=(i,))
- t.start()
- threads.append(t)
- for t in threads:
- t.join() #Must execute join, wait for the execution of the child process to end, and then execute the main process
- result.append(t.get_result())
- 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:
- import threading
- Import Queue
- def is_even(value, q):
- if value % 2 == 0:
- q.put(True)
- else:
- q.put(False)
- def multithreading():
- q = Queue.Queue()
- threads = []
- results = []
- for i in range(10):
- t = threading.Thread(target=is_even, args=(i, q))
- t.start()
- threads.append(t)
- for thread in threads:
- thread.join() #Wait for the end of the child thread, and then execute it later
- for _ in range(10):
- results.append(q.get())
- print(results)
- 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:
- import threadpool
- # Check if the value is even
- def is_even(value):
- if value % 2 == 0:
- return True
- else:
- return False
- #Callback function, the accepted parameters (the request itself, and the execution result of the request work function) can be omitted
- results = []
- def get_result(request, result):
- global results
- results.append(result)
- # 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)
- data = range(10)
- # Declare a pool that can accommodate five threads
- pool = threadpool.ThreadPool(5)
- #Create a thread running content request list (thread work function, thread work parameter list, callback function)
- requests = threadpool.makeRequests(is_even, data, get_result)
- # Throw each thread request into the thread pool
- [pool.putRequest(req) for req in requests]
- #Wait for the data to be consumed and all threads to finish running.
- pool.wait()
- print results
Running the above example, the returned results are as follows:
- C:\Python27\python.exe D:/bluekingProject/wd-test/app-publish/test.py
- [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.