I am launching a main Thread from my Python 3.4 program that launches various subthreads (in this case daemon threads).
I would like to kill the main thread and start it back up again.
For some reason this is an incredibly difficult task. Before someone suggests that I use a multiprocessing.Process and Process.terminate() instead of a Thread, I am unable to go this route because my real program has to share a common sqlite3 connection with all the threads and subthreads, which I cannot do using processes.
Currently, I am using a Queue to signal to the main thread that it should exit using sys.exit(), but this does not work, as you can see below. I've tried os._exit(0) instead, but that kills the whole interpreter.
import sys
import time
from threading import Thread
from queue import Queue
t = None
q = None
def subthread1():
while True:
time.sleep(2)
print(' 1...')
def subthread2():
while True:
time.sleep(2)
print(' 2...')
def main_thread(q):
t1 = Thread(target=subthread1)
t1.daemon = True
t1.start()
t2 = Thread(target=subthread2)
t2.daemon = True
t2.start()
while True:
msg = q.get()
if msg == 0:
print("EXITING THREAD")
sys.exit()
def start():
print("STARTING")
global q, t
q = Queue()
t = Thread(target=main_thread, args=(q,))
t.start()
def kill():
print("KILLING")
global q, t
q.put(0)
def main():
start()
time.sleep(10)
kill()
time.sleep(10)
start()
if __name__ == '__main__':
main()
This produces output:
STARTING
1...
2...
1...
2...
2...
1...
1...
2...
2...
1...
KILLING
EXITING THREAD
2...
1...
1...
2...
2...
1...
2...
1...
STARTING
2...
1...
2...
1...
2...
1...
2...
1...
2...
1...
1...
2...
1...
2...
1...
I want the main thread, including all subthreads, to exit, and then start up again. How can I achieve this? In my real program my subthreads have subthreads (all daemon). Any help greatly appreciated!