I understand that threads generate multiple methods by threading, and it's almost like parallel processing, but what should I do if I want the return value of the method?Ideally, I wish I could add all the return values...
First of all, is the way of thinking wrong?
def pulse(x,y):
sums = x + y
returnsums
pulse_threads=[ ]
for i in range (1,3):
pulse_thread=threading.Thread(target=pulus,args=(i,i))
pulse_threads.append(pulse_thread)
pulse_thread.start()
for pulse_thread in pulse_threads:
pulse_thread.join()
Depending on the purpose, you can easily implement it this time using ThreadPoolExecutor
from concurrent.futures
.
from concurrent.futures import ThreadPoolExecutor
def pulse(x,y):
sums = x + y
returnsums
with ThreadPoolExecutor(max_workers=10) as executor:
x = range (5)
y=range(5,10)
res=executor.map(pulus,x,y)
print(list(x))
print(list(y))
print(list(res))
ThreadPoolExecutor
is often used when I/O is a bottleneck.If you want to distribute heavy processing across multiple CPUs, the ProcessPoolExecutor
might be better.
"If you search ""python multithread return value"", you will see many things."
The English version of StackOverflow looked good.
1. How to use Threadpool in the multiprocessing module
The best answer is to create a thread pool with apply_async and get the results.
However, there seems to be a lot of controversy about the best answer.
How to get the return value from a thread in python?
https://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python
Related
How to obtain the results from a pool of threads impython?
https://stackoverflow.com/questions/26104512/how-to-obtain-the-results-from-a-pool-of-threads-in-python/26104609#26104609
2. How to use Queue in Queue module
In the best answer, a Queue is created first, and the Queue is designated as a parameter of each thread, and the thread packs the result into Queue.
A caller performs a total or average desired processing from the end of all threads until the result of Queue disappears.
There seems to be room for discussion here, too.
Return value from thread
https://stackoverflow.com/questions/1886090/return-value-from-thread
3.Reference
From the Python module description site
threading – Manage concurrent threads
https://pymotw.com/2/threading/
multiprocessing —Manage Processes Like Threads
https://pymotw.com/3/multiprocessing/index.html
© 2024 OneMinuteCode. All rights reserved.