【发布时间】:2021-11-29 17:19:29
【问题描述】:
我的问题:启动一个线程函数并异步根据返回的值进行操作
我知道如何:
- 使用
threading启动线程函数。问题:没有简单的方法可以返回结果 - get the return value 来自线程函数。问题:它是同步的
我想要实现的和 JavaScript 类似的
aFunctionThatReturnsAPromise()
.then(r => {// do something with the returned value when it is available})
// the code here runs synchronously right after aFunctionThatReturnsAPromise is started
在伪 Python 中,我会考虑类似(将示例从 the answer 修改为链接线程)
import time
import concurrent.futures
def foo(bar):
print('hello {}'.format(bar))
time.sleep(10)
return 'foo'
def the_callback(something):
print(f"the thread returned {something}")
with concurrent.futures.ThreadPoolExecutor() as executor:
# submit the threaded call ...
future = executor.submit(foo, 'world!')
# ... and set a callback
future.callback(the_callback, future.result()) # ← this is the made up part
# or, all in one: future = executor.submit(foo, 'world!', callback=the_callback) # in which case the parameters probably would need to be passed the JS way
# the threaded call runs at its pace
# the following line is ran right after the call above
print("after submit")
# after some time (~10 seconds) the callback is finished (and has printed out what was passed to it)
# there should probably be some kind of join() so that the scripts waits until the thread is done
如果可能的话,我想留在线程中(它们按照自己的节奏做事,我不在乎它们何时完成),而不是 asyncio(我必须在单个线程中明确地 await 事情)
【问题讨论】:
标签: python python-3.x multithreading callback asynccallback