EnToutCas
EnToutCas

Reputation: 1357

Exit a process while threads are sleeping

In a python script, I started a bunch of threads, each of which pulls some resource at an interval using time.sleep(interval). I have another thread running, which uses the cmd module to monitor user inputs. When the user enters 'q', I call

sys.exit(0)

However, when the script is running and I enter 'q', the thread user input monitoring thread is quit, but the sleeping threads are still alive. (meaning the program does not exit)

I'm wondering if I'm doing it the right way?

Upvotes: 1

Views: 2441

Answers (1)

Filip Korling
Filip Korling

Reputation: 615

sys.exit will only stop the thread it executes from. If you have other non-daemon thread in your program they will continue to execute. Section 17.2.1 of the Python library docs contains:

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.

See also Why does sys.exit() not exit when called inside a thread in Python?.

Upvotes: 5

Related Questions