• notice
  • Congratulations on the launch of the Sought Tech site

Explain in detail the three ways Python gets the return value of the thread

method one

Use a list of global variables to hold the return value

ret_values = []

def thread_func(*args):
    ...
    value = ...
    ret_values.append(value)

One reason to choose lists is that their append() methods are thread-safe, and in CPython, the GIL prevents concurrent access to them. If you use a custom data structure, you need to add thread locks where the data is modified concurrently.

If you know in advance how many threads there are, you can define a fixed-length list and store the return value according to the index, for example:

from threading import Thread

threads = [None] * 10
results = [None] * 10

def foo(bar, result, index):
    result[index] = f"foo-{index}"

for i in range(len(threads)):
    threads[i] = Thread(target=foo, args=("world!", results, i))
    threads[i].start()

for i in range(len(threads)):
    threads[i].join()

print(" ".join(results))


Method Two

Override the join method of Thread to return the return value of the thread function

The default thread.join() method just waits for the end of the thread function and has no return value. We can return the running result of the function here. The code is as follows:

from threading import Thread


def foo(arg):
    return arg


class ThreadWithReturnValue(Thread):
    def run(self):
        if self._target is not None:
            self._return = self._target(*self._args, **self._kwargs)

    def join(self):
        super().join()
        return self._return


twrv = ThreadWithReturnValue(target=foo, args=("hello world",))
twrv.start()
print(twrv.join()) # hello world will be printed here.

In this way, when we call thread.join() to wait for the thread to end, we also get the return value of the thread.


Method three

Use the standard library concurrent.futures

I think the first two methods are too low-level. Python's standard library concurrent.futures provides more advanced thread operations, which can directly obtain the return value of the thread, which is quite elegant. The code is as follows:

import concurrent.futuresdef foo(bar):    return barwith concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:    to_do = []    for i in range(10): # Simulate multiple tasks        future = executor.submit(foo, f"hello world!{i}")        to_do.append(future)    for future in concurrent.futures.as_completed(to_do): # Concurrent execution        print(future.result())

The result of one run is as follows:

hello world! 8
hello world! 3
hello world! 5
hello world! 2
hello world! 9
hello world! 7
hello world! 4
hello world! 0
hello world! 1
hello world! 6


last words

This article shares 3 methods for obtaining the return value of the thread, and the third method is recommended

So far, this article about the three ways to get the return value of a thread in Python is introduced. For more information about getting the return value of a thread in Python

Original address: https://mp.weixin.qq.com/s/SB7D_FkCOunUYgXaWM-ozw


Tags

Technical otaku

Sought technology together

Related Topic

0 Comments

Leave a Reply

+