简体   繁体   English

Python中的线程/多处理

[英]Threading/Multiprocessing in Python

I have the following code: 我有以下代码:

import SimpleHTTPServer
import SocketServer

def http_server():
    PORT = 80
    Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    httpd = SocketServer.TCPServer(("", PORT), Handler)
    httpd.serve_forever()

The problem with this is that, because of httpd.serve_forever() , it hangs the rest of the program. 这样做的问题在于,由于httpd.serve_forever() ,它会挂起程序的其余部分。 I'm assuming I could use threading to run this on its own thread, so the rest of the program can execute independently of the server, but I'm not sure how to implement this. 我假设我可以使用线程在自己的线程上运行它,所以程序的其余部分可以独立于服务器执行,但我不知道如何实现它。

Simplest way, straight from the docs : 最简单的方法,直接来自文档

from threading import Thread

t = Thread(target=http_server)
t.start()

Note that this thread will be difficult to kill as-is, KeyboardInterrupts do not propagate to random threads that you've start() ed. 请注意,此线程很难按原样终止,KeyboardInterrupts不会传播到您已start()编辑的随机线程。 You may want to set daemon=True or have some more sophisticated method to shut it down. 您可能希望设置daemon=True或使用一些更复杂的方法来关闭它。

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

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