키보드 누화가 여기에서 작동하지 않는 이유는 누구든지 말해 줄 수 있습니까? CTRL + C를 눌러 두 스레드를 종료해야합니다. 두 개의 스레드 - 타이머 스레드와 웹 서버 스레드. join()
의 전화를하기 전에, BCZ 스레드가 완료 될 때까지 기다리고 있습니다 조인 다음 except KeyboardInterrupt
의 무언가를 인쇄 할 수멀티 스레드에서의 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()
코드를 더 잘 읽으려면 들여 쓰기를 수정하십시오. –
완료. 희망은 지금 더 좋아. 감사합니다 –
들여 쓰기가 아직 해제되었습니다. 수업 내 코드를 확인하십시오. 특히 –