简体   繁体   English

为什么python中的这个线程没有停止?

[英]Why is this thread in python not stopping?

I am trying to setup a simple http server in python in a thread. 我正在尝试在python中的线程中设置一个简单的http服务器。

class MyHandler(SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/shutdown':
            print 'Got shutdown request'
            self.server.running = False  
        self.send_response(200)

class Server():

  def __init__(self):
     self._http_server = HTTPServer(('0.0.0.0', 8123), MyHandler)
     self._http_server.running = True
     self._http_server_thread = threading.Thread(target = self._run_http_server, name = 'serverthread')
     self._http_server_thread.start()


  def _run_http_server(self):
      print 'Server started'
      while( self._http_server.running ):
          self._http_server.handle_request()

      print 'Server finished serving'
      self._http_server.shutdown()


  def check_status(self):
      l = threading.enumerate()
      for i in l:
          print i.name


serv = Server()
print 'Sleeping for 20 seconds'
time.sleep(20)
req = urllib2.urlopen('http://127.0.0.1:8123/shutdown')
print 'Finished sleeping'
serv.check()

My assumption is once the _run_http_server finishes running , the thread should stop running but it doesn't.I get this output but the thread keeps running. 我的假设是_run_http_server完成运行后,线程应该停止运行,但是没有。我得到了这个输出,但是线程一直在运行。 Can anyone point why the thread doesn't stop? 谁能指出为什么线程不停止?

Server started
Sleeping for 20 seconds
Got shut down request
127.0.0.1 - - [09/Jul/2016 12:17:17] "GET /shutdown HTTP/1.1" 200 -
Server finished serving
Finished sleeping
MainThread
serverthread
True

In your code you have your own request processing loop (instead of using HTTPServer.serve_forever() ). 在代码中,您有自己的请求处理循环(而不是使用HTTPServer.serve_forever() )。 Yet, you call HTTPServer.shutdown() whose job is to tell the serve_forever() loop to stop and wait until it does. 但是,您调用HTTPServer.shutdown()的工作是告诉serve_forever()循环停止并等待直到停止。 Since serve_forever() wasn't even started, shutdown() never returns (it is actually waiting for serve_forever() to start and immediately stop). 由于serve_forever()甚至还没有启动,所以shutdown()永远不会返回(它实际上正在等待serve_forever()启动并立即停止)。 Removing the self._http_server.shutdown() line fixes the problem. 删除self._http_server.shutdown()行可解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM