Ivan
Ivan

Reputation: 13

Starting thread after thread is finished

Lets say I want to run 10 threads at same time and after one is finished start immediately new one. How can I do that?

I know with thread.join() I can wait to get finished, but than 10 threads needs to be finished, but I want after one finished to start new one immediately.

Upvotes: 1

Views: 1524

Answers (1)

abhira0
abhira0

Reputation: 410

Well, what I understand is that you need to execute 10 thread at the same time.

I suggest you to use threading.BoundedSemaphore()

A sample code on using it is given below:

import threading
from typing import List


def do_something():
    print("I hope this cleared your doubt :)")


sema4 = threading.BoundedSemaphore(10)
# 10 is given as parameter since your requirement stated that you need just 10 threads to get executed parallely

threads_list: List[threading.Thread] = []
# Above variable is used to save threads

for i in range(100):
    thread = threading.Thread(target=do_something)
    threads_list.append(thread)  # saving thread in order to join it later
    thread.start()  # starting the thread

for thread in threads_list:
    thread.join() # else, parent program is terminated without waiting for child threads

Upvotes: 1

Related Questions