同时运行Python线程

时间:2017-05-26 19:39:54

标签: python multithreading concurrency process multiprocessing

我想要同时运行两个函数,因为我想继续在socket中发送和接收消息。这是我的主要功能,但我不能让线程同时运行。仅发送正在运行。我该如何解决这个问题?

def __init__(self):
    d = {}
    d["id"] = "MyId"
    d["Count"] = 0
    d["Message"] = "Just a little message for you"
    self.d = d

    restart = False
    self.restart = self

def sendMessage(self):
    server = SocketServer.UDPServer((DEFAULT_IP, HOST_PORT), MyMessageHandler)
    while True:
        time.sleep(5)
        sendData = json.dumps(self.d, ensure_ascii=False)
        server.socket.sendto(sendData, (DEFAULT_IP, SENDING_PORT))
        self.restart = True

def receiveMessages(self):
    #I know there isn't a message being received. The count is an example of me
    #'receiving' data and then sending it out
    msg_count = 0
    while True:
        if self.restart == True:
            msg_count = 0
            self.d["Count"] = 0
            self.restart = False
        else:
            msg_count += 1
            self.d["Count"] = msg_count
def main(self):
    receiving = threading.Thread(target=self.receiveMessages)
    sending = threading.Thread(target=self.sendMessage(self.d))
    receiving.start()
    sending.start()

    receiving.join()
    sending.join()

2 个答案:

答案 0 :(得分:0)

  

问题:仅发送正在运行。我该如何解决这个问题?

当您将sendMessage(self.d)的结果传递给method sendMessage(self.d)参数时,target只会执行一次。 改为

sending = threading.Thread(target=self.sendMessage)

答案 1 :(得分:0)

您对sending = threading.Thread(target=self.sendMessage(self.d))的来电实际上是在调用函数sendMessages。 此函数是阻塞的,永远不会返回,因此代码永远不会到达receiving.start(),接收线程永远不会运行。

更改为sending = threading.Thread(target=self.sendMessage),所有人都将开始工作。