Queue (Threads)

Geoff Gerrietts geoff at gerrietts.net
Fri Apr 12 15:16:39 EDT 2002


Quoting Thomas Guettler (pan-newsreader at thomas-guettler.de):
> I tried to find examples for the Queue class with google, but
> no look. Has someone links to exmamples or hints?

The code below allows a main thread to delegate a Command to a
subthread. The producer (main thread) calls 

  threads.queue(func, (arg,arg,arg,matey), {'kw': 'kval'})

The consumer threads (StoutpamThread instances) pluck functions off
the queue and run them all day long.

Enjoy,
--G.



""" threads.py
    Implements threading for Stoutpamphlet.

    To delegate a process to a thread, call threads.queue(func, args, kw)

    To check whether you're inside a thread or not, (for example to decide
    whether you want to lock the gui or not) call threads.in_subthread()
"""

has_threads = 0
try:
    import threading, Queue
    has_threads = 1
except:
    pass

if has_threads:
    
    ActivityQueue = Queue.Queue(5)

    def queue(func, args=(), kw={}):
        ActivityQueue.put((func,args,kw))

    class StoutpamThread(threading.Thread):
        def run():
            while (1):
                func, args, kw = ActivityQueue.get()
                apply(func,args,kw)
            # end loop
        # end def

    threads = []
    for i in range(3):
        t = StoutpamThread(name="Thread %d" % (i,))
        threads.append(t)
    # end loop

    def in_subthread():
        t = threading.currentThread()
        return ("MainThread" == t.getName())
else:
    
    def queue(func, args, kw):
        apply(func, args, kw)

    def in_subthread():
        return 0
    



-- 
Geoff Gerrietts             "I am always doing that which I can not do, 
<geoff at gerrietts net>     in order that I may learn how to do it." 
http://www.gerrietts.net                    --Pablo Picasso





More information about the Python-list mailing list