Simple threading

Grant Edwards grante at visi.com
Sat Nov 25 15:22:30 CET 2006


On 2006-11-25, Gabriel Genellina <gagsl-py at yahoo.com.ar> wrote:

>>I'm just getting started on threading and was wondering why the
>>following code does not work (i know globals is bad style - I'll
>>eliminate them eventually).  All I get is a blank cursor flashing.
>
> You've got your example already working. Globals are bad
> style, but worse, threads and globals don't mix very well: you
> need some sort of syncronization for accessing globals 
> (specially for writing them).

That depends on the type of the global and how they're used.
Re-binding a name is always an atomic operation.  Modifying
many mutable objects is atomic.

>>class ImapThread(threading.Thread):
>>     def run(self):
>>         global g_currenttick
>>         if time.time() > (g_datum + (g_secondspertick *
>>g_currenttick)):
>>             print "Ticked %s" % g_currenttick
>>             g_currenttick=g_currenttick+1
>>             print g_currenttick
>
> Having more than one thread, g_currenttick could have been modified 
> *after* you read its value and *before* you write it back, so you 
> lose the count.

Right. Reading an integer object in one statement and writing
it in a subsequent statement is not an atomic opteration unless
protected by some synchronization mechanism.

-- 
Grant Edwards
grante at visi.com




More information about the Python-list mailing list