2

I have this two threads python program that should stall start_events thread when a receive event happens and there's no message in the call_queue, but when I run the program it just ends itself before another one sends a message to it.

import Queue
import threading
import argparse
import socket, struct

call_queue = Queue.Queue()

def call(host, port, localCounter):
   s = socket.socket()
   print "Call: " + host + ", " + str(port) + ", " + str(localCounter)
   s.connect((host, port))
   print s.recv(1024)
   s.send(str(localCounter))


def start_events(events):
   log = [];
   localCounter = 0;
   received = False;
   for e in events:
      localCounter += 1;
      event_parts = e.split()

      if event_parts[0]=="call":
         call(event_parts[1], int(event_parts[2]), localCounter)
         print "call"

      elif event_parts[0]=="receive":
         while call_queue.empty():
            #do nothing
            pass
         remoteCounter = int(call_queue.get())
         print "recahed here"
         if remoteCounter>=0:
            remoteCounter += 1
            localCounter = max(localCounter, remoteCounter)
            received = True
            print "received"
            #print "not recived"

      log.append([e, localCounter])
   print log

def start_listening(port):
   s = socket.socket()
   host = socket.gethostname()
   print "REeceive: " + host + ", " + str(port)
   s.bind((host,port))
   s.listen(5)
   while True:
      c, addr = s.accept()
      call_queue.put(c.recv(1026))
      c.close()
      print "lol"

   #q.put(urllib2.urlopen(url).read())

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('file')
    parser.add_argument('port', type=int)
    res = parser.parse_args()
    inputfile = res.file
    port = res.port

    with open(inputfile) as f:
      inputRaw = f.readlines()
    # you may also want to remove whitespace characters like `\n` at the end of each line
    events = [x.strip() for x in inputRaw]


    #start events thread
    events_thread = threading.Thread(target=start_events, args = (events,))
    events_thread.daemon = True
    events_thread.start()

    #start listening thread
    listening_thread = threading.Thread(target=start_listening, args = (port,))
    listening_thread.daemon = True
    listening_thread.start()

    print port

1 Answers1

0

Your code is finishing instantly because you start the threads and do not wait for them to finish. To do so, you must call join() for each thread you started, in your case this means adding:

events_thread.join()
listening_thread.join()

See this answer for details.

Community
  • 1
  • 1
acidtobi
  • 1,375
  • 9
  • 13