0

编辑问题以删除其他错误


我有一个程序,一旦进程完成就不会加入。我怎样才能让它正确加入?

import time
import sys
import zmq
from multiprocessing import Process, Pipe

def client(address, pipe_send):
    try:
        context = zmq.Context()
        socket = context.socket(zmq.PAIR)
        socket.setsockopt(zmq.RCVTIMEO,5000)
        socket.connect(address)
        print("client connected")    
        while True:
            msg = str(pipe_send.recv())
            print("CLIENT $$",msg)
            if msg:
                socket.send_unicode(msg)
                recv_msg = socket.recv_unicode()
                print("CLIENT ::", recv_msg)
            else:
                break
    except:
        print(
            "client exited with '%s' while multiprocessing" 
            % (sys.exc_info(),)
        )
        
def server(address):
    try:
        context = zmq.Context()
        socket = context.socket(zmq.PAIR)
        socket.setsockopt(zmq.RCVTIMEO,5000)
        socket.bind(address)
        while True:
            try:
                msg = socket.recv_unicode()
                print("SERVER ::",msg)
                socket.send_unicode("Message sent successfully")
                time.sleep(1)
            except:
                break
    except:
        print(
            "server exited with '%s' while multiprocessing" 
            % (sys.exc_info(),)
        )
        
if __name__ == "__main__":
    req_pipe, rep_pipe = Pipe()
    addr = "tcp://127.0.0.1:1235"
    s = Process(target=server,args=(addr,))
    s.start()
    c = Process(target=client,args=(addr,rep_pipe))
    c.start()
    for i in range(10):
        req_pipe.send(i)
    
    s.join()
    c.join()
4

2 回答 2

2
s = Process(target=server,args=(addr,)).start()

您已将 s 定义为 的返回值start(),而不是Process它本身,并且start()must的返回值是None没有 join 方法的。

于 2013-08-08T17:01:29.153 回答
1
  • 不要分配Proces(..).start()s/ c
  • 发送标记值以通知数据结束。我用过''

if __name__ == "__main__":
    req_pipe, rep_pipe = Pipe()
    addr = "tcp://127.0.0.1:1235"
    s = Process(target=server,args=(addr,))
    s.start()
    c = Process(target=client,args=(addr,rep_pipe))
    c.start()
    for i in range(10):
        req_pipe.send(i)
    req_pipe.send('') # End of data.

    c.join()
    s.join()
于 2013-08-08T17:23:31.350 回答