我想同時運行兩個函數,因爲我想繼續在套接字中發送和接收消息。這是我的主要功能,但我無法讓線程同時運行。只有發送正在運行。我怎樣才能解決這個問題?同時運行Python線程
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()
你能分享在兩個線程中運行的代碼嗎? – srfrnk
多重處理對你沒用嗎? – Mikael
@srfrnk我將代碼添加到問題 – user3358710