Threading
Published Jun 3, 2022Updated Dec 21, 2022
Contribute to Docs
The threading
module allows multiple threads of execution to take place in a Python program.
While threads may appear to run simultaneously, only one thread can be executed at a time. This is enforced by Python’s global interpreter lock.
Threading is helpful when working with tasks that are I/O bound. This includes web-oriented tasks like scraping or downloading files.
Syntax
import threading
The threading
module must first be imported before thread constants can be created and their methods can be used.
Example
The following example features five threads that are created, started, and end at different points before the program finishes:
import threading, time, random# simulates waiting time (e.g., an API call/response)def slow_function(thread_index):time.sleep(random.randint(1, 10))print("Thread {} done!".format(thread_index))def run_threads():threads = []for thread_index in range(5):individual_thread = threading.Thread(target=slow_function, args=(thread_index,))threads.append(individual_thread)individual_thread.start()# at this point threads are running independently from the main flow of application and each otherprint("Main flow of application")# This ensures that all threads finish before the main flow of application continuesfor individual_thread in threads:individual_thread.join()print("All threads are done")run_threads()
This results in output like the following:
Main flow of applicationThread 1 done!Thread 4 done!Thread 3 done!Thread 2 done!Thread 0 done!All threads are done
Threading
- .is_alive()
- Returns True if the thread is still running and False, otherwise.
- .join()
- Delays the flow of execution of a program until the target thread is completely read.
- .local()
- Returns a local thread object with data that is specific to that thread.
- .run()
- Executes any target function belonging to a given thread object that is now active.
- .start()
- Activates and prompts a thread object to be run.
- .Thread()
- Returns a thread object that can run a function with zero or more arguments.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours