so I am trying to start a new thread from an RPC call from a C++ program to a within a Flask server with the following code
@api.route("/open_api_connection")
def open_api_connection():
# spawn server
from threading import Thread
thread = Thread(target = start_message_server)
thread.start()
return jsonify({"host":"localhost", "port":8080})
def start_message_server():
while True:
time.sleep(1)
print "in server"
But when I send an HTTP request to this server via a C++ program the Flask server becomes impossible to kill with a CTRL-c. I am guessing the new thread somehow becomes a zombie. ps
reveals that the process is still running even after a CTRL-c. CTRL-z does not work either... I am starting the Flask server with the inbuilt server like so
api = Flask(__name__)
# import stuff ...
if __name__ == "__main__":
# check if the port number that is used to run this script has been
# provided or not
if len(sys.argv) == 2:
port = sys.argv[1]
else:
sys.stderr.write("Usage: python " + sys.argv[0] + " <port_number>\n")
sys.exit(1)
api.run(port = int(sys.argv[1]), threaded = True)
I am connecting to this server via a call in C++ like so
open_connection("localhost", "8000");
Any ideas why this would be happening and how I can resolve this issue?
See the documentation here:
A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.
A python process will only exit when all non-daemon threads have exited. The main thread is the one dealing with a standard ctrl-c event (usually the unix signal SIGINT), and will exit when it receives that. Any other, non-daemon threads, will either (a) need to realize that the main thread has exited and then exit themselves, or (b) be daemon threads that exit automatically when all other threads have exited.
When creating the thread, try instead:
thread = Thread(target=start_message_server)
thread.daemon = True
thread.start()
When created in this way, the thread should not prevent the process from shutting down, if it is the only thing running.