简体   繁体   中英

python asyncio: how to best use lock threads?

Let's imagine I have a thread with an asyncio event loop and other threads running.

I may have to deal with synchronisation between threads with the lock mecanism for instance. But the lock may block the coroutine... And no other tasks (in the asyncio thread) will run concurrently.

What is the solution ? My guess is that a kind of lock primitivve which would be asynchronous could do the job but it does not exist as far as I know.

To be precise: I do not refer to the existing asyncio lock primitive.

Use loop.run_in_executor to run a synchronous call in a thread:

def synchronous_function():
    with synchronous_lock:
        # Do something

async def asynchronous_function():
    await loop.run_in_executor(None, synchronous_function)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM