簡體   English   中英

關閉 http.server.HTTPServer 是否保證線程安全?

[英]Is closing http.server.HTTPServer guaranteed to be thread-safe?

from http.server import HTTPServer, SimpleHTTPRequestHandler
import threading

with HTTPServer(("localhost", 8080), SimpleHTTPRequestHandler) as httpd:
    threading.Thread(target=httpd.serve_forever, daemon=True).start()
    # Do something ...

當程序退出with塊時,是否保證httpd正確關閉? 例如,如果httpd在代碼到達with塊的末尾時正在傳輸數據,那么該連接是否會被正確切斷(或等待它完成)?

我的理解是ThreadingHTTPServer應該正確處理這些,因為文檔說:

socketserver.ThreadingMixIn.server_close()等待所有非守護線程完成,除非socketserver.ThreadingMixIn.block_on_close屬性為 false。 通過將ThreadingMixIn.daemon_threads設置為 True 以不等到線程完成來使用守護線程。

但是我想看看Python最基本的內置http服務器HTTPServer是否也能正確處理這個問題。

http.server.HTTPServersocketserver.BaseServer的子類。TCPServer 是socketserver.TCPServer的子類。 BaseServer中定義.serve_forever 在這里,在不同的線程中關閉.serve_forever的正確方法是調用.shutdown() 這是您在with語句結束之前應該做的事情。

現在回答您提出的問題:當您不調用.shutdown()時, serve_forever會做什么? 好吧,我不確定。 __exit__ function 僅關閉套接字,不進行任何清理。 The answer appears to be 'Whatever your OSes implementation of select.select does when it has no sockets to select over.' 這是什么? 顯然,在 Unix 上就像什么都沒發生一樣繼續,在 Windows 上引發異常? 這意味着在 Unix 上,服務器將永遠繼續服務,而在 Windows 上它將引發異常。 (請注意,我對此不確定。只需.shutdown()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM