簡體   English   中英

為什么我的進程不加入python?

[英]Why won't my processes join in python?

已編輯問題,以刪除其他錯誤


我有一個程序,一旦程序完成就不會加入。 我怎樣才能使其正確加入?

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()
s = Process(target=server,args=(addr,)).start()

您已將s定義為start()的返回值,而不是Process本身,並且start()的返回值必須為None ,它沒有join方法。

  • 不要將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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM