cost of creating threads

Bryan Olson bryanjugglercryptographer at yahoo.com
Thu Sep 30 21:02:44 CEST 2004


Ajay wrote:
> i have an application that runs on a pocket pc. 
[...]
> my question is, in terms of memory and processing
> power, how much overhead will creating threads cost.

I've never worked with Pocket-PC, but the answer is almost 
certainly "not much".  You can get reasonable bounds with simple 
test programs.  I'll include a Python thread creation timer 
below.

Threading has improved vastly in recent years, and the current 
versions of the popular operating systems now have excellent 
thread support.  As one might expect, out-dated ideas about 
the cost of threads are still widespread.


--Bryan



import thread
import time

lock = thread.allocate_lock()
lst = [0]

def increment():
    lock.acquire()
    lst[0] += 1
    lock.release()

def mass_thread(nthreads):
    print "Running %d threads..." % nthreads
    i = 0
    benchmark = time.clock()
    while i < nthreads:
        try:
            thread.start_new_thread(increment, ())
            i += 1
        except:
            #  thread.error is undocumented, so catch all
            time.sleep(0.05)
    go = 1
    while go:
        time.sleep(0.1)
        lock.acquire()
        if lst[0] == nthreads:
            go = 0
        lock.release()
    benchmark = time.clock() - benchmark
    print "All %s threads have run." % lst[0]
    print "That took %f seconds." % benchmark

if __name__ == '__main__':
    mass_thread(10000)



More information about the Python-list mailing list