multithreading - 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!
解决方案
推荐阅读
- javascript - 如何从这些数据中获取这些值
- laravel - 在 belongsToMany-relation 中按枢轴值搜索项目
- azure - 在 Azure 逻辑应用中,如何使用 NTLM 身份验证进行 HTTP Get/Post 调用?
- python - 如何使用 GrabCut 分割算法从二值图像中提取 ROI
- css - 如何将地图图标保持在作为背景图像的地图的相同位置?CSS
- flutter - 更新正文的颤振按钮
- flutter - Flutter - MultiProvider(ChangeNotifierProvider)不起作用
- java - 如何根据与 Java 7 兼容的出现顺序对单词的字母进行排序?
- javascript - 选择单选按钮时显示消息
- sql-server - 具有多个不同 where 子句的 SQL Server 存储过程动态 SQL