Demonic and non-demonic threads

It must be noted that the thread is invoked from the main program and the main program will not exit (by default) until the thread is executed completely. The reason is that the main program invokes the thread by default in non-demonic mode, which makes the thread run in the foreground rather than wait for it to run in the background. Thus, a non-demonic thread is one that runs in the foreground, causing the main program to wait for the running threads to finish their execution. A demonic thread, on the other hand, is one that runs in the background, therefore not causing the main program to wait for it to finish its execution. Take a look at the following example:

As can be seen from the preceding code snippet, when we create and execute a non-demonic thread (default), after printing Main Ended, the Terminal window halts for 4 seconds, waiting for the ND thread to finish its execution. When it finishes, we get an  Exit Non Demonic message, which is when the main program exits. Up until this point, the main program would not exit.

Let's see how this changes with demonic threads, which run in the background:

In the preceding code snippet, we saw how to make use of a demonic thread. Interestingly enough, the main program did not wait for the demonic thread to finish execution. The demonic thread ran in the background and by the time it finished, the main thread had already exited from the memory, and thus we did not see the Exit :Daemonic message printed on the screen. In this case, we are making use of the logging module. By default, the logging module will log to the stdout, which, in our case, happens to be the Terminal.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.119.17