setDaemon() method of threading.Thread

Here is some basic code using threading:

import Queue
import threading

def basic_worker(queue):
    while True:
        item = queue.get()
        # do_work(item)
        print(item)
        queue.task_done()
def basic():
    # http://docs.python.org/library/queue.html
    queue = Queue.Queue()
    for i in range(3):
         t = threading.Thread(target=basic_worker,args=(queue,))
         t.daemon = True
         t.start()
    for item in range(4):
        queue.put(item)
    queue.join()       # block until all tasks are done
    print('got here')

basic()

When you run it, you get

% test.py
0
1
2
3
got here

Now comment out the line:

         t.daemon = True

Run it again, and you’ll see that the script prints the same result, but hangs.
The main thread ends (note that got here was printed), but the second thread never finishes.

In contrast, when t.daemon is set to True, the thread t is terminated when the main thread ends.

Note that “daemon threads” has little to do with daemon processes.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)