Python 异步协议竞争条件

Python asyncio protocol race conditions

考虑以下代码(解释如下):

import asyncio

class MyClass(object):
    def __init__(self):
        self.a = 0
    def incr(self, data):
        self.a += 1
        print(self.a)

class GenProtocol(asyncio.SubprocessProtocol):
    def __init__(self, handler, exit_future):
        self.exit_future = exit_future
        self.handler = handler

    def pipe_data_received(self, fd, data):
        if fd == 1:
            self.handler(data)
        else:
            print('An error occurred')

    def process_exited(self):
        self.exit_future.set_result(True)

def start_proc(stdout_handler, *command):
    loop = asyncio.get_event_loop()
    exit_f = asyncio.Future(loop=loop)
    subpr = loop.subprocess_exec(lambda: GenProtocol(stdout_handler, exit_f),
                                 *command,
                                 stdin=None)
    transport, protocol = loop.run_until_complete(subpr)

    @asyncio.coroutine
    def waiter(exit_future):
        yield from exit_future

    return waiter, exit_f

def main():
    my_instance = MyClass()
    loop = asyncio.get_event_loop()
    waiter, exit_f = start_proc(my_instance.incr, 'bash', 'myscript.sh')
    loop.run_until_complete(waiter(exit_f))
    loop.close()

if __name__ == '__main__':
    main()

组件的简要说明如下:

  1. MyClass很直接
  2. GenProtocol 是一个 class,它允许为子进程的标准输出上接收到的数据指定自定义处理程序。
  3. start_proc 允许您启动自定义进程,通过 GenProtocol
  4. 为在 stdout 上接收到的数据指定自定义处理程序
  5. my_proc 是一个永远运行的进程,在任意时间向管道发送数据

现在我的问题如下:由于我使用方法作为处理程序,并且由于该方法以非原子方式更改实例属性,这是否存在潜在危险?例如,当我在子进程的管道上异步接收数据时,处理程序是否同时被调用两次(因此有可能破坏 MyClass.a 中的数据)或者它是否被序列化(即第二次调用处理程序时它没有执行直到第一个完成)?

协议方法是常规函数,不是协程。 他们里面没有屈服点

所以执行顺序非常简单:所有调用都是序列化的,竞争条件是不可能的。

UPD

示例中的 pipe_data_received() 不是协程,只是一个没有 await / yield from 的函数。

asyncio 总是一次执行全部,中间没有任何上下文切换。

您可能认为 pipe_data_received() 受锁保护,但实际上这种情况不需要任何锁。

当你有这样的协程时,锁是强制性的:

async def incr(self):
    await asyncio.sleep(0.1)
    self.counter +=1

在后者中 incr() 是一个协程,而且,在 sleep() 调用时上下文切换是很有可能的。如果你想保护并行递增,你可以使用 asyncio.Lock():

def __init__(self):
    self.counter = 0
    self._lock = asyncio.Lock()

async def incr(self):
    async with self._lock:
        await asyncio.sleep(0.1)
        self.counter +=1