Python threading (was: Re: global interpreter lock not working as it should)

Jonathan Hogg jonathan at onegoodidea.com
Sun Aug 4 17:45:24 EDT 2002


On 4/8/2002 21:54, in article m3bs8imjkd.fsf at mira.informatik.hu-berlin.de,
"Martin v. Loewis" <martin at v.loewis.de> wrote:

> bokr at oz.net (Bengt Richter) writes:
> 
>> A mutex should result in a context switch every time there is a release with
>> a waiter present, since the releaser would reliably fail to re-acquire.
>> Perhaps that is the way it works on BSD? That might at least partly explain
>> Jonathan's results.
> 
> I doubt that. 

I dunno. The numbers seem to make sense. My test code involves 10 threads in
a tight loop counting iterations and a very loose count of thread switches.
The way it counts thread switches is to check each time through the loop if
it was the last thread (according to a global variable) and set that
variable (and count) if not. Look at the numbers:

Counts:
[29676, 34221, 15907, 15857, 15815, 15782, 15756, 15734, 15714, 15697]
Total = 190159

Switches:
[15933, 15915, 15907, 15856, 15815, 15782, 15756, 15734, 15714, 15697]
Total = 158109

You'll note that the numbers very quickly tend towards there having been at
least one thread switch (I can't count any more finely than that) on each
loop iteration.

The loop disassembles to 27 bytecodes. So the threads must be getting
switched every GIL release (or possibly every second GIL release, but 2 is
an unlikely number in the world of physics ;-)). This is also played out by
the fact that the first two threads dominate the iteration count. The loop
that starts the threads is 9 bytecodes long, and clearly it only manages to
start two threads before a switch to one of them occurs.

Jonathan




More information about the Python-list mailing list