When it comes to threads, your brain should have this impression: We can control when it starts, but we cannot control when it ends. So how to get the return value of the thread? Today I will share some of my own practices.
1 2 3 4 5 6 |
|
One reason for choosing a list is that the append() method of the list is thread-safe. In CPython, the GIL prevents their concurrent access. If you use a custom data structure, you need to add a thread lock where the data is modified concurrently.
If you know how many threads there are in advance, you can define a fixed-length list, and then store the return value according to the index, for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
The default thread.join() method just waits for the thread function to end and has no return value. We can return the running result of the function here. The code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
In this way, when we call thread.join() and wait for the thread to end, we will get the return value of the thread.
I think the first two methods are too low-level. Python’s standard library concurrent.futures provides more advanced thread operations and can directly obtain threads. The return value is quite elegant. The code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
The result of a certain operation is as follows:
1 2 3 4 5 6 7 8 9 10 |
|
The above is the detailed content of Three ways to get thread return value in Python. For more information, please follow other related articles on the PHP Chinese website!