terminate a program gracefully from a thread

Dave Angel davea at davea.name
Sat Mar 22 14:18:52 CET 2014

 Jabba Laci <jabba.laci at gmail.com> Wrote in message:
> Hi,
> I have a script (see below) that I want to terminate after X seconds.
> The main loop of the program is waiting for user input.
> The program enters the main loop and I try to shut down the program
> after X seconds from a thread but I can't figure out how to do it. The
> program should also do some cleanup before termination, so the shut
> down must be graceful.
> The code below is a simplified version. The whole idea is the
> following: I have a script that has grown quite big over time. It
> needs to read several data files, so when I start it for the first
> time, it takes about 3-4 seconds to launch. The next start is much
> faster since, I guess, the OS has done some caching. I use this script
> a lot and the first slow launch bothers me. My idea: after booting, I
> want to start the script in the background in suicide mode. OS does
> the caching, so when I need it, it starts quickly.

You need a flag to indicate that a particular invocation is the
 dummy one (background). So use that same flag either to suppress
 starting the thread,  or to avoid the unwanted raw_input.

If you had no blocking I/o, you could use a simple global to
 notify all the threads. Or use a signal to abort the main thread
 if it's stuck in raw_input. 

Alternatively,  rethink the need to preload at boot time.  Any
 caching the OS does is likely to only last a few minutes, 
 depending on load. So maybe you can make the real load seem to be
 quicker by displaying the gui right away,  but doing the
 time-consuming part in a thread. 

More information about the Python-list mailing list