Sim*_*ini 4 thread-safety multiprocessing race-condition python-3.x python-asyncio
考虑以下代码(解释如下):
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()
Run Code Online (Sandbox Code Playgroud)
组件的简要说明如下:
MyClass 很简单GenProtocol 是一个允许为在子进程的标准输出上接收的数据指定自定义处理程序的类。start_proc 允许您启动自定义进程,为在 stdout 上接收的数据指定自定义处理程序,通过 GenProtocolmy_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
Run Code Online (Sandbox Code Playgroud)
后者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
Run Code Online (Sandbox Code Playgroud)