简体   繁体   English

同时运行Python线程

[英]Running Python threads concurrently

I have two functions I want to run concurrently, as I want to keep sending and receiving messages in my socket. 我想同时运行两个函数,因为我想继续在套接字中发送和接收消息。 This is my main function, but I can't get the threads to run concurrently. 这是我的主要功能,但是我无法让线程同时运行。 Only sending is running. 仅发送正在运行。 How can I fix this? 我怎样才能解决这个问题?

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

Question : Only sending is running. 问题 :仅发送正在运行。 How can I fix this? 我怎样才能解决这个问题?

Your sendMessage(self.d) is only executed once as you pass the result of the method sendMessage(self.d) to the target parameter. sendMessage(self.d) method sendMessage(self.d)的结果传递给target参数时,只会执行一次 method sendMessage(self.d)
Change to 改成

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

Your call to sending = threading.Thread(target=self.sendMessage(self.d)) is actually calling the function sendMessages . 您对sending = threading.Thread(target=self.sendMessage(self.d))的调用实际上是在调用sendMessages函数。 This function is blocking and will never return thus the code will never reach receiving.start() and the receiving thread will never run. 该函数处于阻塞状态,并且永远不会返回,因此代码将永远不会到达receiving.start() ,并且接收线程将永远不会运行。

Change to sending = threading.Thread(target=self.sendMessage) and all will start working. 更改为sending = threading.Thread(target=self.sendMessage) ,所有这些都将开始工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM