title: Communicating from main code to multiple threads (that have sockets, if that matters)
body: <p>I've been reading up on threading, sockets, and queues but still have a mental block on how this all works.  Right now I have a threaded server that accepts connections on a port and then spins off a new thread (and new, randomly assigned system port) to handle the remaining work.  What I'd like to do is from the main thread, communicate to the sub-threads and send them work to do.  here is an example of my threaded server:</p>
  
  <pre><code>import threading, time, socket
  
  class ClientThread(threading.Thread):
  
      def __init__(self,ip,port,clientsocket):
          threading.Thread.__init__(self)
          self.ip = ip
          self.port = port
          self.csocket = clientsocket
          print ("[+] New thread started for "+ip+":"+str(port))
  
      def run(self):
          # Stuff happens here
          # keep alive
          while True:
              #send a keepalive to the network device
              data = 'someinfo'
              self.csocket.sendall(data)
              #receive keepalive
              data = self.csocket.recv(56)
              time.sleep(8)
  
  while True:
      host = "127.0.0.1"
      port = 3000
      tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
      tcpsock.bind((host,port))   
      tcpsock.listen(5)
      print ("\nListening for incoming connections...")
      (clientsock, (ip, port)) = tcpsock.accept()
      newthread = ClientThread(ip, port, clientsock)
      newthread.start()
  </code></pre>
  
  <p>So there is a super simple example of my server that accepts incoming connections and spins off threads to keep the connections active.  What I would love to do now, is encorporate queues to allow me to send 'data' to an individual thread to be sent to the network device, and then get its response from the device.  In this way I can interact with multiple devices through their individual thread/socket all from my main code.  I just need a little help figuring out the best way to do this.  </p>
  
  <p>If it's a queue, how do I tell the queue which thread to talk to?</p>
  
  <p>Thank you in advance!</p>
  
  <p>[EDIT 1]</p>
  
  <p>For sake of example, let's say these devices are simple devices that turn on a relay.  So each would connect to the main thread, get their separate threads spawned, and then just send responses to the keep alive.  At any time, I'd like to either interrupt the keep alive or just send my command after to say, turn on a relay or turn a relay off.  The device will perform the command and then respond with (confirmed, error, etc).  The main thread would receive this response from the sub-thread and then prompt for a new command or just wait while the keep-alive runs.  So I could sit at a terminal and turn relays on and off.</p>