Skip to main content
 首页 » 编程设计

python之在 Python 中使异步调用同步

2025年05月04日12www_RR

使异步调用看起来同步的最佳方法是什么?例如,类似这样,但我如何协调调用线程和异步回复线程?在 Java 中,我可能会使用带超时的 CountdownLatch(),但我找不到适用于 Python 的明确解决方案

def getDataFromAsyncSource(): 
    asyncService.subscribe(callback=functionToCallbackTo) 
    # wait for data 
    return dataReturned 
 
def functionToCallbackTo(data): 
    dataReturned = data 

请您参考如下方法:

有一个模块可以使用

import concurrent.futures 

查看此帖子以获取示例代码和模块下载链接:Concurrent Tasks Execution in Python

您可以将执行器结果放在未来,然后获取它们,这里是来自 http://pypi.python.org 的示例代码:

import concurrent.futures 
import urllib.request 
 
URLS = ['http://www.foxnews.com/', 
    'http://www.cnn.com/', 
    'http://europe.wsj.com/', 
    'http://www.bbc.co.uk/', 
    'http://some-made-up-domain.com/'] 
 
def load_url(url, timeout): 
    return urllib.request.urlopen(url, timeout=timeout).read() 
 
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: 
    future_to_url = dict((executor.submit(load_url, url, 60), url) 
                     for url in URLS) 
 
    for future in concurrent.futures.as_completed(future_to_url): 
        url = future_to_url[future] 
        if future.exception() is not None: 
            print('%r generated an exception: %s' % (url,future.exception())) 
        else: 
            print('%r page is %d bytes' % (url, len(future.result())))