Thursday, March 6, 2014

Daemon Threads Explanation

Some threads do background tasks, like sending keepalive packets, or performing periodic garbage collection, or whatever. These 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, you'd have to keep track of them, and tell them to exit, before your program can completely quit. By setting them as daemon threads, you can let them run and forget about them, and when your program quits, any daemon threads are killed automatically.

Let's say you're making some kind of dashboard widget. As part of this, you want it to display the unread message count in your email box. So you make a little thread that will:
    1.    Connect to the mail server and ask how many unread messages you have.
    2.    Signal the GUI with the updated count.
    3.    Sleep for a little while.
When your widget starts up, it would create this thread, designate it a daemon, and start it. Because it's a daemon, you don't have to think about it; when your widget exits, the thread will stop automatically.

Does Queue.get block main?

Yes -- if you call some_queue.get() within either the thread or the main function, the program will block there until some object as passed through the queue.

However, it is possible to use queues so that they don't block, or so that they have a timeout of some kind:
import Queue

while True:
    try:
        data = some_queue.get(False) 
        # If `False`, the program is not blocked. `Queue.Empty` is thrown if
        # the queue is empty
    except Queue.Empty:
        data = None

    try:
        data2 = some_queue.get(True, 3) 
        # Waits for 3 seconds, otherwise throws `Queue.Empty`
    except Queue.Empty:
        data = None

You can do the same for some_queue.put -- either do some_queue.put(item, False) for non-blocking queues, or some_queue.put(item, True, 3) for timeouts. If your queue has a size limit, it will throw a Queue.Full exception if there is no more room left to append a new item.

My Profile

My photo
can be reached at 09916017317