Learn

We have seen how to create a thread in Python; however, we didn’t see any speed or efficiency benefits in our previous example.

To see the benefits of threading, let’s learn how to create multiple threads and test them out in our example.

When creating multiple threads throughout this course, we will use one of the following approaches:

# create each thread t1 = threading.Thread(target=target_function, args=(arg1,)) t2 = threading.Thread(target=target_function, args=(arg2,)) t3 = threading.Thread(target=target_function, args=(arg3,)) # start each thread t1.start() t2.start() t3.start()

or

threads = [] # list of arguments to use args = [arg1, arg2, arg3] # iterate through the length of arguments for i in range(len(args)): # create thread t = threading.Thread(target=target_function, args=(args[i],)) # add thread to threads list threads.append(t) # start thread t.start()

The benefit of the second approach is that it keeps track of our threads in a list called threads. In the next exercise, we will see why this is helpful. Therefore, we will follow this approach going forward.

Instructions

1.

In script.py, we have some code set up for you. greeting_with_sleep() is loaded in; however, this time, it does not have the timer code. Instead, a function called main_threading() contains the timer code. In this function, you will write code to create and initiate four threads.

Inside main_threading(), write a for loop that iterates through greetings. Inside this for loop:

  • Create a thread called t that has greeting_with_sleep() as its target and takes one arg from greetings at each iteration.
  • Start the created thread.

For now, do not worry about creating a threads list.

Finally, call main_threading().

Inside the terminal output, type python3 script.py and press Enter. To check your answer, click Check Work once your program finishes running.

Does your output make sense?

2.

In the terminal, you should see something similar to the following:

Codecademy Chelsea Hisham Ashley Threading Elapsed Time: 0.0005821380036650226 seconds says hello! says hello! says hello! says hello!

You also may have noticed that the following showed up instantaneously:

Codecademy Chelsea Hisham Ashley Threading Elapsed Time: 0.0005821380036650226 seconds

But after about two seconds, the next messages showed up:

says hello! says hello! says hello! says hello!

We will explore this some more in the next exercise. However, to give you a brief explanation. Each thread has started, but Python is waiting for the last thread to finish before terminating. Therefore, while main_threading() has completed, greeting_with_sleep() is still executing the final thread.

To move onto the next exercise, click Check Work.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?