【发布时间】:2018-06-30 11:53:32
【问题描述】:
我正在尝试制作一个程序,该程序会产生两个相互通信的进程。我已经阅读了关于协程的内容,并认为这次采用它会很好,并且由于协程在使用之前需要准备好,所以我认为最好让装饰器自动执行此操作。
import multiprocessing as mp
import random
import time
import os
from datetime import datetime, timedelta
from functools import wraps
output, input = mp.Pipe()
def co_deco(func):
@wraps(func)
def wrapper(*args, **kwargs):
cr = func(*args, **kwargs)
cr.send(None)
return cr
return wrapper
class sender(mp.Process):
def __init__(self, pipe):
mp.Process.__init__(self)
self.pipe = pipe
def run(self):
print('RECEIVER PID: ', os.getpid() )
while True:
self.pipe.send( random.randint(0,10) )
time.sleep(1)
class receiver(mp.Process):
def __init__(self, pipe):
mp.Process.__init__(self)
self.pipe = pipe
def run(self):
while True:
self.coroutine.send( self.pipe.recv() )
@co_deco
def coroutine(self):
while True:
msg = yield
print( datetime.now(), msg )
if __name__ == '__main__':
mp.freeze_support()
sen = sender(pipe=input)
rec = receiver(pipe = output)
sen.start()
rec.start()
sen 进程每秒向rec 进程发送一个随机整数。每当一个整数到达时,coroutine 方法(rec)将其绑定到msg 并与当前时间一起打印出来。
我发现代码没有问题,但它显示了一条错误消息:
self.coroutine.send( self.pipe.recv() )
AttributeError: 'function' object has no attribute 'send'
我认为装饰协程存在问题,但我不知道究竟是什么问题以及如何解决它。我想得到一些帮助。
【问题讨论】:
标签: python python-decorators coroutine