简体   繁体   中英

python threading - multiple parameter and return

I have a method like this in Python:

def test(a,b):
    return a+b, a-b

How can I run this in a background thread and wait until the function returns.

The problem is the method is pretty big and the project involves GUI, so I can't wait until it's return.

In my opinion, you should besides this thread run another thread that checks if there is result. Or Implement callback that is called at the end of the thread. However, since you have gui, which as far as I know is simply a class -> you can store result into obj/class variable and check if the result came.

I would use mutable variable, which is sometimes used. Lets create special class which will be used for storing results from thread functions.

import threading
import time
class ResultContainer:
    results = [] # Mutable - anything inside this list will be accesable anywher in your program

# Lets use decorator with argument
# This way it wont break your function
def save_result(cls):
    def decorator(func):
        def wrapper(*args,**kwargs):
            # get result from the function
            func_result = func(*args,**kwargs)

            # Pass the result into mutable list in our ResultContainer class
            cls.results.append(func_result)

            # Return result from the function
            return func_result

        return wrapper

    return decorator

# as argument to decorator, add the class with mutable list
@save_result(ResultContainer)
def func(a,b):
    time.sleep(3)
    return a,b


th = threading.Thread(target=func,args=(1,2))
th.daemon = True
th.start()

while not ResultContainer.results:
    time.sleep(1)
print(ResultContainer.results)

So, in this code, we have class ResultContainer with list . Whatever you put in it, you can easily access it from anywhere in the code (between threads and etc... exception is between processes due to GIL). I made decorator , so you can store result from any function without violating the function. This is just example how you can run threads and leave it to store result itself without you taking care of it. All you have to do, is to check, if the result arrived.

You can use global variables, to do the same thing. But I dont advise you to use them. They are ugly and you have to be very careful when using them.


For even more simplicity, if you dont mind violating your function, you can just, without using decorator, just push result to class with list directly in the function, like this:

def func(a,b):
    time.sleep(3)
    ResultContainer.results.append(tuple(a,b))
    return a,b

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM