我正在一个新线程中启动一个HTTPServer
对象:
from http.server import HTTPServer, SimpleHTTPRequestHandler
import threading
with HTTPServer(("localhost", 8080), SimpleHTTPRequestHandler) as httpd:
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
thread.start()
# Doing my work ...
httpd.shutdown()
在这里,我想确保httpd.serve_forever()
在到达# doing my work...
之前已经成功启动。我当然可以在thread.start()
之后插入thread.join(timeout=1)
,但这仍然有种族条件的风险。是否有可靠的方法等待serve_forever
启动并运行?
当然。有一个名为service_actions
的回调,它在serve_forever
循环的每次迭代后都会被调用,您可以在其中使用threading.Event()
来等待
由于回调是在每个可能服务的请求之后调用的,它将导致长达0.5秒的初始延迟(默认情况下(,但我认为这不是问题。如果是,您可以覆盖serve_forever
,以便在第一个请求服务之前执行此操作。
import threading
from http.server import HTTPServer, SimpleHTTPRequestHandler
class SignalingHTTPServer(HTTPServer):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.ready_event = threading.Event()
def service_actions(self):
self.ready_event.set()
with SignalingHTTPServer(("localhost", 8080), SimpleHTTPRequestHandler) as httpd:
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
thread.start()
httpd.ready_event.wait()
# Doing my work ...
httpd.shutdown()