简体   繁体   中英

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.
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 . This function is blocking and will never return thus the code will never reach receiving.start() and the receiving thread will never run.

Change to sending = threading.Thread(target=self.sendMessage) and all will start working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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