user3732793
user3732793

Reputation: 1959

Why is Python3 daemon thread instantly closing in console?

this code works in idle3 but in a console(MAC, Windows Linux) thread2 is instantly closing if set to daemon. Is there any explanation for that ? Maybe also a workaround to properly have a daemon thread asking for user input ?

import queue
import threading
import sys

def worker(q):
    _text = ''
    while _text == '':
        _text = q.get()
        print('[worker]input was ',_text)
    sys.exit()

def dialog(q):
    while True:
        try:
            _select = input('[dialog]enter text:')
            if _select != '':
            q.put(_select)
        except EOFError:
            pass
        except KeyboardInterrupt:
            print("bye")
            sys.exit(0)
        except Exception as e:
            print(e)
            sys.exit(1)
        if 'esc'.lower() in _select.lower():
            sys.exit()

q = queue.Queue()
thread1 = threading.Thread(target=worker,args=(q,))
thread2 = threading.Thread(target=dialog,args=(q,))
thread1.setDaemon(True)
thread2.setDaemon(True)
print('start asking')
thread1.start()
thread2.start()

thanks for any hint on the issue

Upvotes: 1

Views: 193

Answers (1)

R. van Schijndel
R. van Schijndel

Reputation: 36

Normally the child threads die when the main thread exits. The code you've given as example exits directly after starting two child threads. To solve this, you should 'join' the threads back to the main thread. This will make it so the main thread waits for the child threads to die.

thread1.join()
thread2.join()

at the end of your file should solve this problem.

https://docs.python.org/3.5/library/threading.html#threading.Thread.join

Also, why do you want to run this application as daemon?

Upvotes: 2

Related Questions