4

I'm updating some existing code that looks like this:

for i in list
  thread.start_new_thread(main, (i[0],i[1],i[2],2))

This causes threads to be created for every item in the list, but not executed until all the threads are created. I'd like to either execute the threads in small groups, or just have them execute directly after they're created.

(There are a lot of python threads discussion on here so sorry if I missed this type of question already being asked...)

1
  • start_new_thread as its name suggests starts new thread immediately. Note thread module had been deprecated by threading module since 2005. Commented Dec 2, 2012 at 20:51

1 Answer 1

4

You may find the concurrent.futures module useful. It's available also for Python 2 under the name futures. For example, to invoke a function main for every item on MY_LIST concurrently, but with at most 5 threads, you can write:

from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=5) as executor:
    for result in executor.map(main, MY_LIST):
        # Do something with result
        print(result)
Sign up to request clarification or add additional context in comments.

1 Comment

This worked pretty well actually. I feel I should be able to implement this in native code. No?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.