Using asyncio for Non-async Functions in Python?

前端 未结 2 371
轻奢々
轻奢々 2020-12-20 21:33

Suppose there is a library that makes various database queries:

import time

def queryFoo():
    time.sleep(4)
    return \"foo\"

def queryBar():
    time.s         


        
2条回答
  •  一整个雨季
    2020-12-20 22:00

    I presume you are after concurrency and hopefully do not insist on using asyncio module itself in which case this little example could be helpful:

    import asyncio
    import time
    from concurrent.futures import ThreadPoolExecutor
    
    def queryFoo():
        time.sleep(2)
        return "FOO"
    
    def queryBar():
        time.sleep(4)
        return "BAR"
    
    with ThreadPoolExecutor(max_workers=2) as executor:
        foo = executor.submit(queryFoo)
        bar = executor.submit(queryBar)
        results = [foo.result(), bar.result()]
    
    print(results)
    

    It runs both queryFoo() and queryBar() in parallel and collects their results in a list in order in which they've been mentioned in an assignment to results.

提交回复
热议问题