python asyncio.Event.wait() 没有响应 event.set()

标签 python python-asyncio

计划是让多个 IO 例程“同时”运行(特别是在 Raspberry Pi 上,同时操作 IO 引脚和运行 SPI 接口(interface))。我尝试使用 asyncio 来实现这一点。但是,我的简单试用拒绝运行。
这是代码的简化版本,省略了 IO 引脚详细信息:

"""\
Reduced problem representation:
this won't run because GPIO details have been left out
"""

import RPi.GPIO as gpio
import asyncio

GPIO_PB = 12         # Define pushbutton channel

async def payload():
    """ Provides some payload sequence using asyncio.sleep() """
    #Payload action
    await asyncio.sleep(1)
    #Payload action
    await asyncio.sleep(1)

class IOEvent(asyncio.locks.Event):
    """\
    Create an Event for asyncio, fired by a callback from GPIO
    The callback must take a single parameter: a gpio channel number
    """
    def __init__(self, ioChannel, loop):
        super().__init__(loop = loop)
        self.io = ioChannel

    def get_callback(self):
        "The callback is a closure that knows self when called"
        def callback( ch ):
            print("callback for channel {}".format(ch))
            if ch == self.io and not self.is_set():
                print(repr(self))
                self.set()
                print(repr(self))
        return callback

async def Worker(loop, event):
    print("Entering Worker: {}".format(repr(loop)))
    while loop.is_running():
        print("Worker waiting for {}".format(repr(event)))
        await event.wait()
        print("Worker has event")
        event.clear()
        await payload()
        print("payload ended")

loop = asyncio.get_event_loop()

# Create an event for the button
pb_event = IOEvent( GPIO_PB, loop)

# register the pushbutton's callback
# Pushing the button calls this callback function
gpio.add_event_callback( GPIO_PB, pb_event.get_callback() )

try:
    asyncio.ensure_future(Worker(loop, pb_event))
    loop.run_forever()
except KeyboardInterrupt:
    pass
finally:
    print("Closing Loop")
    loop.stop()
    loop.close()

我得到的输出是这样的:
Entering Worker: <_UnixSelectorEventLoop running=True closed=False debug=False>
Worker waiting for <__main__.IOEvent object at 0x76a2a950 [unset]>
callback for channel 12
<__main__.IOEvent object at 0x76a2a950 [unset,waiters:1]>
<__main__.IOEvent object at 0x76a2a950 [set,waiters:1]>
callback for channel 12

这些行显示按钮重复并正确触发其回调例程。第一次调用set()功能符合预期。用于 wait() 的事件调用和set()调用是一样的。但是消息“ worker 有事件”,在 await event.wait() 之后电话永远不会出现。

我看了PyQt5 and asyncio: yield from never finishes ,但我没有看到除默认循环之外的任何其他循环。

为什么wait()永远不会回来?我怎么知道?

最佳答案

add_event_callback 设置的回调从不同的线程调用,如它们被“在后台”自动调用所示。这意味着您不能调用 setasyncio.Event直接来自 gpio 回调,因为 asyncio 类不是线程安全的。
唤醒 asyncio.Event从不同的线程,您可以传递 event.setloop.call_soon_threadsafe .在你的情况下,你会改变:

self.set()
到:
self._loop.call_soon_threadsafe(self.set)

关于python asyncio.Event.wait() 没有响应 event.set(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48836285/

相关文章:

Python asyncio (aiohttp, aiofiles)

Django 3.0 — 异步测试后数据库连接未关闭

python-3.x - 为什么我无法通过 Discord.py 从函数发送消息?

python - 我如何等待来自另一个线程和另一个循环的 asyncio.Future

python - 如何在Python中从列表中选择一些项目?

python - 从字符串中删除非数字字符

python - 由于与 GI 相关的 python 脚本中的错误,Gnome 终端未启动

python - 检查 pandas DataFrame 系列中的值是否存在于 Excel 工作表中

python - Python Flask Web 服务中带有回调的长异步计算

python - 与 python 模型相比,tensorflow lite 模型给出了非常不同的精度值