python while循环在它应该之前结束

时间:2017-04-15 19:48:50

标签: python

我有这两个线程python程序,当接收事件发生时,应该停止start_events线程,并且call_queue中没有消息,但是当我运行程序时,它只是在另一个程序向其发送消息之前结束

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 个答案:

答案 0 :(得分:0)

您的代码即将完成,因为您启动了线程并且不等待它们完成。为此,您必须为您启动的每个主题调用join(),在您的情况下,这意味着添加:

events_thread.join()
listening_thread.join()

有关详细信息,请参阅this答案。