Answer the question
In order to leave comments, you need to log in
How to send a message from a thread to another thread in Python?
I have a small Python application that accepts connections from clients. Each connection is defined in a separate thread. It is necessary to implement a connection between two random clients.
In this case, each stream is assigned a name that is taken from the data sent by the client (for example, "id1"). After 4 clients (id1-id4) have connected, id5 connects and at this moment it is necessary to send a message to id3 that 5 has arrived. I mean, if self.getName() == 'id5', then... what?
Or does it make sense to implement it somehow differently? Collect connections in an array and then look for the one to send to on it? How to implement this option in the code, in this case?
import pickle, socket, threading, string
stat = True
class ClientThread(threading.Thread):
def __init__(self, channel, details):
self.channel = channel
self.details = details
threading.Thread.__init__(self)
def run(self):
data = self.channel.recv(1024)
self.setName(data)
print self.getName()
self.channel.close()
print 'Closed connection:', self.details[0]
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind('8.8.8.8', 8088)
server.listen(5)
while stat:
channel, details = server.accept()
ClientThread(channel, details).start()
Answer the question
In order to leave comments, you need to log in
I didn’t dig deep myself (the task allowed me to simply connect Celery), but I need to dig towards shared memory , or still rustle the signals in Celery
Schematically so
class ClientThread(threading.Thread):
def sendmsg(self, worker, msg):
worker.msg = msg
def processmsg(self, msg):
do_something(msg)
def run(self):
if name == "id5":
self.sendmsg(worker, msg)
worker = ClientThread(channel, details)
worker.start()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question