Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

like image 443
Novicode Avatar asked Jul 07 '26 22:07

Novicode


1 Answers

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. You may want to set daemon=True or have some more sophisticated method to shut it down.

like image 182
roippi Avatar answered Jul 11 '26 05:07

roippi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!