Limit number of concurrent threads

Chuck May cmay4 at yahoo.com
Tue Sep 24 15:56:08 EDT 2002


That sounds interesting.  I'll try it.

I was just hacking a much less elegant way of doing it.  Here is what I 
came up with:

from threading import Thread
import time, random

maxthreads =  5  # maximum number of concurrent threads
totalops   = 80  # hold total number of operations
all        = {}  # global holding the current running threads

class Worker(Thread):
    global all
    
    def __init__(self, id):
        Thread.__init__(self)
        self.all = all
        self.id = id

    def run(self):
        time.sleep(random.randint(10, 100) / 1000.0)
        print "id %d: " % self.id, all.keys()
        del all[self.id]

if __name__ == "__main__":
    for i in range(totalops):
        while (len(all) > maxthreads):
            time.sleep(.1)
            
        all[i] = 1
        w = Worker(i)
        w.start()

There may be problems with that, but it does seem to work.

Syver Enstad <syver-en+usenet at online.no> wrote in
news:uwupbdwnj.fsf at online.no: 

> Chuck May <cmay4 at yahoo.com> writes:
> 
>> I've searching for examples that fit my problem, and I haven't found 
>> any.  Most examples I've found look something like this:
>> 
>>     threads = []
>>     for i in range(number_of_tasks):
>>         thread.append(thread_for_task)
>>     
>>     # let the threads run - just wait for shutdown
>>     for t in threads:
>>         t.join() 
>> 
>> which whould work fine if I wanted to start all 80 threads at once.
>> 
>> I've read about the Queue, but I'm not sure if it's what I want, and
>> I 
>> 
>> can't seem to find any good examples on it.
> 
> I think Queue would be nice to use, Have a thread (the main thread
> perhaps) feed all the table names (or a table object if you please)
> into a Queue. 
> 
> Set up some worker threads with access to the Queue
> (global variable, member). The worker threads should loop something
> like this:
> 
> while 1:
>    queueItem = self._queue.get()
>    doSomethingWithQueueItemHere
> 
> Then you can start your workers.
> 
> (You'll have to find out some way to make the workers exit when the
> work is done, perhaps putting a number of None's equal to the number
> of workers last in the queue and testing for None in the working
> thread loop. 
> 
> 



-- 
Chuck May
IMS, Inc.
may at ims.nci.nih.gov



More information about the Python-list mailing list