【问题标题】:Pyserial and asyncioPyserial 和 asyncio
【发布时间】:2017-02-17 13:46:15
【问题描述】:

尝试在 Windows 机器上使用 pyserial 和 asyncio。

https://stackoverflow.com/a/27927704/1629704 的启发,我的代码一直在监视串行端口的传入数据。

# This coroutine is added as a task to the event loop.
@asyncio.coroutine
def get_from_serial_port(self):
    while 1:
        serial_data = yield from self.get_byte_async()
        <doing other stuff with serial_data>

# The method which gets executed in the executor
def get_byte(self):
    data = self.s.read(1)
    time.sleep(0.5)
    tst = self.s.read(self.s.inWaiting())
    data += tst
    return data

# Runs blocking function in executor, yielding the result
@asyncio.coroutine
def get_byte_async(self):
    with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
        res = yield from self.loop.run_in_executor(executor, self.get_byte)
        return res

串行数据返回后。在 while 循环中调用协程 get_byte_async,创建一个新的执行器。我总是知道创建一个新线程很昂贵,所以我觉得我应该采取另一种方法,但我不知道该怎么做。 我一直在看这篇文章https://hackernoon.com/threaded-asynchronous-magic-and-how-to-wield-it-bba9ed602c32#.964j4a5s7

我想我需要在另一个线程中读取串行端口。但是如何将串行数据返回到“主”循环?

【问题讨论】:

标签: python python-asyncio


【解决方案1】:

您可以使用默认执行程序并使用asyncio lock 锁定对get_byte 的访问:

async def get_byte_async(self):
    async with self.lock:
        return await self.loop.run_in_executor(None, self.get_byte)

或者简单地创建一次你自己的执行器:

async def get_byte_async(self):
    if self.executor is None:
        self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
    return await self.loop.run_in_executor(self.executor, self.get_byte)

【讨论】:

    猜你喜欢
    • 2023-02-02
    • 1970-01-01
    • 2021-10-06
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多