我正在开发一个简单的应用程序来测试Python中的Pipes。应用程序启动一个新进程,作为" server"。 "服务器"启动另外两个工作进程,将一些数据发送到"服务器"当"服务器"接收消息时,应该更新其状态,将其发送给所有工作人员以及主进程。但是应用程序在收到278条消息后总是停止。我究竟做错了什么? 这是代码:
class Server ( multiprocessing.Process ):
def __init__( self, connection ):
super( Server, self ).__init__()
self.conn = connection
def run( self ):
state = []
conn1a, conn1b = multiprocessing.Pipe()
conn2a, conn2b = multiprocessing.Pipe()
p1 = multiprocessing.Process( target=worker, args=(conn1b, 2, 'p1', 1 ) )
p2 = multiprocessing.Process( target=worker, args=(conn2b, 3, 'p2', -1 ) )
p1.start()
p2.start()
counter = 0
while 1:
if conn1a.poll() or conn2a.poll():
if conn1a.poll():
state = conn1a.recv()
if conn2a.poll():
state = conn2a.recv()
self.conn.send( state )
conn1a.send( state )
conn2a.send( state )
counter += 1
print "counter", counter
p1.join()
p2.join()
def worker( conn, seconds, name, multiplier ):
x = 0
conn.send( [name, x*multiplier] )
while 1:
if conn.poll():
x += seconds
time.sleep( seconds )
conn.send( [name, x*multiplier] )
if __name__ == '__main__':
conn1, conn2 = multiprocessing.Pipe( False )
p = Server( conn2 )
p.start()
while 1:
print "received", conn1.recv()
p.join()
申请表的输出如下:
enter codstarting process p2
received ['p2', 0]
counter 1
starting process p1
received ['p1', 0]
counter 2
received ['p1', 2]
counter 3
...
counter 277
received ['p1', 332]
counter 278
received ['p2', -333]
答案 0 :(得分:1)
你忘了读工人的烟斗。管道被填满了。
if conn.poll():
conn.recv() # consume messages!
x += seconds