为什么我的进程不能加入python?

时间:2013-08-08 16:58:19

标签: python process multiprocessing pipe zeromq

编辑问题以删除其他错误


我有一个程序,一旦进程完成就不会加入。如何让它正确加入?

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()

2 个答案:

答案 0 :(得分:2)

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

您已将s定义为start()的返回值,而不是Process本身,start()的返回值必须为None,而不是{{1}}有一个连接方法。

答案 1 :(得分:1)

  • 请勿将Proces(..).start()分配给s / c
  • 发送sentinel值以通知数据结束。我使用了''

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()