In the post Python threading – an intro I introduced something about python threads, I explained the GIL (Global Interpreter Lock) and how to instantiate workers and timers.

The GIL is the topic you must know to take full advantages from python threads.

In this post I’m going to explain the following topics:

  1. Subclassing Thread
  2. Instantiating daemon thread
  3. Listing all instatiated threads
  4. Signaling threads


 – Subclassing Thread

Since the module “threading” is implemented in an object oriented way, every thread corresponds to an object and you can easily subclass it.
The simplest way to subclass is adding a parameter to the initialization and modify the run method to print the passed name:

in this way the subclassed thread will print the name passed as soon as the run method is called:

and the output will be:

 – Instantiating daemon thread
Daemons are only useful when the main program is running, and it’s okay to kill them off once the other non-daemon threads have exited. Without daemon threads, we have to keep track of them, and tell them to exit, before our program can completely quit. By setting them as daemon threads, we can let them run and forget about them, and when our program quits, any daemon threads are killed automatically.

The following code instantiates a daemon and then two workers threads, as soon as the two worker threads terminate the daemon ends its works and the program exits:

 – List all instantiated threads
Python threading module provides the enumerate method to retrieve a list of all Thread objects currently alive.

The list includes daemonic threads, dummy thread objects created by current_thread(), and the main thread. It excludes terminated threads and threads that have not yet been started.

For convenience I’m going to make changes to the previous piece of code:

Then the code for the main will be:

 – Signaling threads
Signaling is useful to wake up threads when a new event is received by a program.

To send signals to threads in python we need an Event object, it can be instantiated as EVT = threading.Event(). Then we can set the event. The set() method does not clear the event so we have to clear it manually. The following code sets and clears the event every 3 seconds:

To receive the signal I’m going to subclass threading.Thread adding a wait_for_event method.
The init method shall accept the event object as parameter then the method wait_for_event shall call the evt.wait().

Now the code for the main program is as follows:

And the output:

As usual you can find the full source code for this post at my github