0

任何人都可以告訴我爲什麼KeyboardInterrupt不在這裏工作?我需要按CTRL + C來結束這兩個線程。兩個線程 - 定時器線程和Web服務器線程。下面是代碼 -Python中KeyboardInterrupt在多線程

import threading 
import thread 
import time 
import urllib2 
import httplib 

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler 
from SocketServer import ThreadingMixIn 
import Queue 
import signal 
import sys 

q = Queue.Queue() 
j = Queue.Queue() 
h = "threading working!" 

class SignalHandler: 
    stopper = None  
    def __init__(self,stopper): 
     self.stopper = stopper 

    def __call__(self, signum, frame): 
     self.stopper.set() 
     sys.exit(0) 

#Timer Thread 
class myThread(threading.Thread): 
    stopper = None 

    def __init__(self, **kwargs): 
     self.req = [] 
     self.stopper = stopper 
     for k, v in kwargs.iteritems(): 
      setattr(self, k, v) 
     threading.Thread.__init__(self) 

    def run(self): 
     while not self.stopper.is_set(): 
      while self.go: 
       try: 
       while True: 
        r = q.get_nowait() 
        self.req.append(r) 
       except Queue.Empty, e: 
        pass 
       t = threading.Timer(1,self.hello, [h]) 
       t.start() 
       time.sleep(1) 

    def hello(self, s): 
     print s   
     while self.req:    
     r = self.req.pop() 
     print "Client Request >>>>>>>", r            
     thread_id = str(threading.currentThread()) 
     j.put(thread_id)         

    def stop(self): 
     print "Stopping thread.." 
     self.go = False 
     try: 
      while True: 
       q.get_nowait() 
      q.task_done() 
     except Queue.Empty, e: 
      pass  

#Webserver thread 
class Handler(BaseHTTPRequestHandler): 

    def do_HEAD(self): 
     self.send_response(200)   
     self.send_header("Content type", "text/html") 
     self.end_headers() 

    def do_GET(self): 
     self.do_HEAD() 
     req = (self.path, self.client_address, self.command,)   
     q.put(req)  
     self.wfile.write("Thread Info: ") 
     self.wfile.write(j.get())     
     return   

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): 
    """Handle requests in a separate thread.""" 

#main 
if __name__ == '__main__': 
    stopper = threading.Event() 
    handler = SignalHandler(stopper) 
    signal.signal(signal.SIGINT, handler) 
    server = ThreadedHTTPServer(('localhost', 8080), Handler) 
    try: 
     timer_thread = myThread(stopper,go=True)   
     timer_thread.start()  
     server_thread = threading.Thread(target=server.serve_forever) 
     server_thread.daemon = True 
     server_thread.start()   
     print 'Starting server, use <Ctrl-C> to stop' 
    except KeyboardInterrupt, e: 
     print "Interrupted" 
     q.join() 
     j.join() 
     timer_thread.stop() 
     timer_thread.join()  
+0

請先修復縮進以幫助更好地閱讀代碼。 –

+0

完成。現在希望它更好。謝謝 –

+0

您的縮進仍然關閉。檢查班級內的代碼,尤其是 –

回答

0

首先,您的實例myThread在創建時出錯,必須是stopper=stopper(關鍵字arg是預期的)。其次,代碼有錯誤,主線程不等待服務器線程,但立即去join() s。所以,except從來沒有發生 - 什麼都不會被打印。主要的bug在join()。加入Python不會因信號而中斷。所以,你必須編寫自己的連接函數,它會以超時(例如1秒)調用原始的join(),但在不定式循環中。更好的是讓加入時間稍短,然後 - sleep() - 睡眠不可中斷。兩者都在循環中。

+0

它工作。謝謝 –

0

嘗試打印東西的except KeyboardInterrupt旁邊,之前調用join() S,BCZ加入正在等待的線程來完成。

+0

它沒有打印它。 –