首页 > 解决方案 > Asyncio threadsafe primitives

问题描述

I need Threadsafe primitives (locking, conditions Semaphore), do they exist in the asyncio ecosystem?

I created some code myself, but it feels a bit sluggish:

import asyncio
from threading import get_ident,Lock,Event

class AsyncThreadsafeEvent():
    def __init__(self,*args,**kwargs):
        super(AsyncThreadsafeEvent, self).__init__()
        self.waiters = {}
        self.event = Event()

    def set(self):
        self.event.set()
        events = self.waiters.values()
        for loop,event in events:
            loop.call_soon_threadsafe(event.set)


    async def wait(self):
        event = asyncio.Event()
        #not strictly necessary but could provide tiny speedup
        if self.event.is_set():
            return

        self.waiters[get_ident()] = (asyncio.get_event_loop(),event)

        #to ensure thread safty
        if self.event.is_set():
            return

        await event.wait()

Any help would be appreciated!

标签: multithreadinglockingpython-asynciopython-multithreading

解决方案


推荐阅读