Handling threads in Python
In this section of the chapter, we'll take a look at how you can effectively create and manage multiple threads in Python programs.
Starting loads of threads
The first example we'll look at is how we can start numerous threads all at once. We can create multiple thread objects by using a for
loop and then starting them within the same for
loop. In the following example, we define a function that takes in an integer and which sleeps for a random amount of time, printing both when it is starting and ending.
We then create a for
loop which loops up to 10, and create 10 distinct thread objects that have their target set to our executeThread
function. It then starts the thread object we've just created, and then we print out the current active threads.
Example
Let's now look at an example:
import threading import time import random def executeThread(i): print("Thread {} started".format(i)) sleepTime = random.randint(1,10) time.sleep(sleepTime) print("Thread {} finished executing...