beginner, thread & else
Fredrik Lundh
fredrik at pythonware.com
Fri Dec 15 01:52:38 EST 2006
Gigs_ wrote:
> can someone explain me this code
did you write that yourself, or did you find it in some book or article?
> ----------------------------------
> import thread
the thread module should not be used directly by application programs;
use the "threading" module instead.
> stdoutmutex = thread.allocate_lock()
> exitmutexes = [0] * 10
>
> def counter(myId, count):
> for i in range(count):
> stdoutmutex.acquire()
> print '[%s] => %s' % (myId, i)
> stdoutmutex.release()
> exitmutexes[myId] = 1 # signal main thread
>
> for i in range(10):
> thread.start_new(counter, (i, 100))
>
> while 0 in exitmutexes:
> pass
that's a "busy loop"; the CPU will spend all the cycles it can get
checking for the condition. that's not a good way to wait for
things.
use the "threading" module instead; by default, it waits for all threads
to finish without requiring flag lists and excessive CPU use.
> print 'Main thread exiting.'
> -----------------------------------
>
> thread.start_new(counter, (i, 100)) is running counter function.
it starts a new instance of counter, in a separate thread.
> Is counter function and while statement executed in same time (other
> things i understand, but can't get into this)?
yes, the while loop will run in the "main" thread, in parallel with the
other threads. however, Python uses a global lock to synchronize access
to Python variables:
http://effbot.org/pyfaq/what-is-the-global-interpreter-lock.htm
so the threads in a simple program like this won't run fully in parallel
on a multi-CPU machine.
</F>
More information about the Python-list
mailing list