簡體   English   中英

同時運行Python線程

[英]Running Python threads concurrently

我想同時運行兩個函數,因為我想繼續在套接字中發送和接收消息。 這是我的主要功能,但是我無法讓線程同時運行。 僅發送正在運行。 我怎樣才能解決這個問題?

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

問題 :僅發送正在運行。 我怎樣才能解決這個問題?

sendMessage(self.d) method sendMessage(self.d)的結果傳遞給target參數時,只會執行一次 method sendMessage(self.d)
改成

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

您對sending = threading.Thread(target=self.sendMessage(self.d))的調用實際上是在調用sendMessages函數。 該函數處於阻塞狀態,並且永遠不會返回,因此代碼將永遠不會到達receiving.start() ,並且接收線程將永遠不會運行。

更改為sending = threading.Thread(target=self.sendMessage) ,所有這些都將開始工作。

暫無
暫無

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

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