2
我有這兩個線程的Python程序,應該停止start_events線程時發生接收事件,並且call_queue中沒有消息,但是當我運行程序它只是在另一個發送之前自己結束自己給它的消息。Python的while循環結束之前,它應該
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