【问题标题】:Why is this thread in python not stopping?为什么python中的这个线程没有停止?
【发布时间】:2016-07-09 19:19:41
【问题描述】:

我正在尝试在一个线程中在 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()

我的假设是一旦 _run_http_server 完成运行,线程应该停止运行但它没有。我得到这个输出但线程继续运行。谁能指出为什么线程不会停止?

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

【问题讨论】:

    标签: python multithreading python-multithreading simplehttpserver


    【解决方案1】:

    在您的代码中,您有自己的请求处理循环(而不是使用HTTPServer.serve_forever())。然而,你打电话给HTTPServer.shutdown(),他的工作是告诉serve_forever() 循环停止并等到它停止。由于serve_forever() 甚至还没有启动,所以shutdown() 永远不会返回(它实际上是在等待serve_forever() 启动并立即停止)。删除self._http_server.shutdown() 行可以解决问题。

    【讨论】:

    • 谢谢!学到了一些东西。
    猜你喜欢
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 2022-09-25
    • 2019-12-21
    • 2020-11-21
    • 2018-05-17
    • 2015-01-10
    • 1970-01-01
    相关资源
    最近更新 更多