Welcome, guest | Sign In | My Account | Store | Cart

You specify it a 'get' function and it runs a thread and gets it for you. Incredibly simple.

Python, 19 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import _thread as thread

class AsyncGetter:
    def __init__(self, method, args=()):
        self.method = method
        self.gotten = False
        self.args = args
        
        thread.start_new_thread(self.doGet, ())
        
    def doGet(self):
        self.result = self.method(*self.args)
        self.gotten = True
        
    def hasGotten(self):
        return self.gotten
    
    def getResult(self):
        return self.result

1 comment

Francis Horsman 10 years, 10 months ago  # | flag

self.result is undefined leading to unexpected AttributeError if getResult() is called before async method returns. A better pattern could be to add a timeout argument to getResult() that waits on a multiprocessing.Semaphore and raises a custom exception if the result is not returned in the required timeout. Without the following modification, async exceptions will not be propagated: Another good feature would be to try/except round line #12 to capture any async exception which could then be directly raised by getResult() if applicable.