basic thread question

Derek Martin code at pizzashack.org
Tue Aug 18 16:10:15 EDT 2009


I have some simple threaded code...  If I run this
with an arg of 1 (start one thread), it pegs one cpu, as I would
expect.  If I run it with an arg of 2 (start 2 threads), it uses both
CPUs, but utilization of both is less than 50%.  Can anyone explain
why?  

I do not pretend it's impeccable code, and I'm not looking for a
critiqe of the code per se, excepting the case where what I've written
is actually *wrong*. I hacked this together in a couple of minutes,
with the intent of pegging my CPUs.  Performance with two threads is
actually *worse* than with one, which is highly unintuitive.  I can
accomplish my goal very easily with bash, but I still want to
understand what's going on here...

The OS is Linux 2.6.24, on a Ubuntu base.  Here's the code:

Thanks

-=-=-=-=-

#!/usr/bin/python

import thread, sys, time

def busy(thread):
    x=0
    while True:
        x+=1

if __name__ == '__main__':
    try:
        cpus = int(sys.argv[1])
    except ValueError:
        cpus = 1
    print "cpus = %d, argv[1] = %s\n" % (cpus, sys.argv[1])
    i=0
    thread_list = []
    while i < cpus:
        x = thread.start_new_thread(busy, (i,))
        thread_list.append(x)
        i+=1
    while True:
        pass

-- 
Derek D. Martin
http://www.pizzashack.org/
GPG Key ID: 0x81CFE75D

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20090818/7b4e1cd8/attachment.sig>


More information about the Python-list mailing list