Python_Dude
Python_Dude

Reputation: 507

Creating many number of threads in python?

I want to create 3 threads in python ,I am using python class thread library, Is this the below is the right way to create threads in while loop? it may create problems?

while (count <= 3):
     try:
        thread = CreateThread(count, args)
        thread.start()
     except:
        logger.error("Error: unable to start thread ")

Any other right ways?

Upvotes: 1

Views: 218

Answers (1)

Serdalis
Serdalis

Reputation: 10489

Although We can't see your actual Thread class i'll assume its correct, there is something in this code that can be improved.

You will want to keep the references to each thread so you can stop / join / wait for them at a later time.

So your code should look more like:

thread = []
for i in range(3):
    try:
        new_thread = CoreRouterThread(count, args)
        new_thread.start()
        # we append the thread here so we don't get any failed threads in the list.
        thread.append(new_thread)
     except:
        logger.error("Error: unable to start thread ")

Upvotes: 3

Related Questions