Reputation: 3675
I have a google cloud function triggered by HTTP request does following two tasks:
def task1():
do sth
return info
def task2(info):
do sth
def main(request)
info=task1()
if (info):
task2(info)
return info
I would like the function returns without waiting the task2 completes. So I did following changes:
import asyncio
def task1():
do sth
return info
async def task2(info):
do sth
async def bar(info):
return await task2(info)
def main(request)
info=task1()
if (info):
asyncio.run(bar(info))
return info
Not sure if I did is correct? But I didn't notice the function gets any faster. Can anyone give me some suggestions?
Upvotes: 0
Views: 973
Reputation: 75715
Coroutines are designed to leverage CPU concurrent processing. Typically, when you can call a URL and wait the response, there is time (some milliseconds). Instead of doing nothing you can use the unused CPU power to process another coroutine. It's more efficient and, ideally, the max processing time is equals to the slowest coroutine (or API call in my example).
in your example, there is no wait, no time where the CPU do nothing (a sleep, a URL call) and thus you can't leverage the concurrency process. In addition, you need to have 2 or more coroutine to see the benefit of concurrent execution.
Upvotes: 1