Spaces:
Sleeping
Sleeping
File size: 1,149 Bytes
c471598 ec9d18e c471598 ff9ac06 c471598 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
"""Turn a sync func to async."""
import asyncio
import functools
from concurrent.futures import ThreadPoolExecutor
def force_async(func):
"""Turn a sync func to async.
Args:
func: a sync func
Return:
async func
Usage:
@force_async
def normal_func():
...
loop = asyncio.get_event_loop()
#~ tasks = [sync_loop1(1, 5), sync_loop1(2, 10)]
#~ res = loop.run_until_complete(asyncio.gather(*tasks)) # OK
res = loop.run_until_complete(
asyncio.gather(
*[
sync_loop1(1, 7),
sync_loop1(2, 6),
sync_loop1(2, 6),
async_func,
]
)
)
"""
# executor = ThreadPoolExecutor()
# from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor(max_workers=10)
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""Preserve func info."""
future = executor.submit(func, *args, **kwargs)
return asyncio.wrap_future(future) # make it awaitable
return wrapper
|