S
S
small-newbie2014-10-14 13:22:05
Python
small-newbie, 2014-10-14 13:22:05

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

UPD: I
figured out the second option like: at the very beginning we create an empty dictionary, and in the run method of the class we put data about the socket into this dictionary (conn[self.getName()] = self). Well, under the condition if self.getName() == 'id5' we do, for example, conn['id3'].channel.send('WOW').
However, is this a good way? Is it worth it to do so?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Lubchich, 2014-10-14
@Cybran

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

V
Valentine, 2014-10-14
@vvpoloskin

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

In general, some kind of storage container is often used for streams - a list, a queue. Look towards ThreadPool

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question