简体   繁体   中英

Python Limit number of threads allowed

For the code segment below, I would like limit the number of running threads to 20 threads. My attempt at doing this seems flawed, because once the counter hits 20, it would just not create new threads, but those values of "a" would not trigger the do_something() function (which must account for every "a" in the array). Any help is greatly appreciated.

count = 0
for i in range(len(array_of_letters)):

    if i == "a":
        if count < 20:
            count=+1 
            t = threading.Thread(target=do_something, args = (q,u))

            print "new thread started : %s"%(str(threading.current_thread().ident))     
            t.start()
            count=-1

concurrent.futures has a ThreadPoolExecutor class, which allows submitting many tasks and specify the maximum number of working threads:

with ThreadPoolExecutor(max_workers=20) as executor:
    for letter in array_of_letters):
        executor.submit(do_something, letter)

Check more examples in the package docs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM