Discover Python with Sparks : A Little Look at Threads
Discover with Sparks provides bite-sized insight into different technologies.?
From foundational concepts for beginners through to specialist engineering principles, you’ll find something new for yourself to Discover with Sparks. See something you want to know more about? Reach out to talk about how we can help you learn more through our training. May
Exploring Threads in Python
Many of us will recognise Python as a popular, high-level programming language that is widely used for its simplicity and readability. If this is your first look at Python or programming, check out our Getting Started with Sparks series for a heads-up on how this stuff works, or our Sparks Ignite videos.
One of the many features Python offers is support for multithreading, which enables software engineers to create concurrent* applications with improved performance and responsiveness.
*Concurrent? Uh… what? This means multiple instructions are being carried out at the same time by your computer, instead of sequentially, which is one-at-a-time.
Let’s take a quick look at threads in Python, discussing the basics of threading, how it is implemented in Python, and providing code examples to illustrate the concepts.?
By the end of this, you will be in with a shout of holding your own in a cafe conversation when you’re talking about the foundations of Python threading. You may even be ready to start implementing threads in your own applications. But your cafe choices may need a little bit of work.
Python Threading Basics
A thread is the smallest unit of execution in a program. A single process can consist of multiple threads, which can be executed concurrently. Threading allows a program to perform multiple tasks simultaneously, improving overall performance, especially in situations where tasks can be executed independently.
Python provides the threading module as part of its standard library, which allows developers to create and manage threads with ease. The threading module is built on top of the lower-level _thread module, which provides a more primitive and less user-friendly interface.
Creating and Running Threads in Python
To create a thread in Python, you need to define a function that will be executed by the thread, and then create a new Thread object from the threading module, passing the function as an argument.
Here's a simple example that demonstrates how to create and run a thread in Python:
领英推荐
import threading
def print_some_numbers():
??for i in range(5):
????print(i)
# Create a new thread and pass the 'print_numbers' function as the target
thread_1 = threading.Thread(target=print_some_numbers)
# Start the thread
thread_1.start()
# Wait for the thread to finish
thread_1.join()
print("Thread execution finished")
In this example, the print_numbers function is executed by the new thread, printing the numbers 0 to 4. The start() method is called to begin the thread's execution, and the join() method is called to wait for the thread to complete before continuing with the rest of the program.
Thread Synchronisation
When multiple threads access shared resources, it's essential to ensure that the threads are properly synchronised to avoid data corruption or other issues. Python provides several synchronisation primitives, such as Locks and Semaphores, to help developers manage access to shared resources.
Here's an example that demonstrates how to use a Lock to synchronise access to a shared resource:
import threading
the_counter = 0
lock = threading.Lock()
def the_count_incrementor():
??global the_counter
??with lock:
????for i in range(2):
??????the_counter += 1
# Create three threads that will increment the counter
thread_1 = threading.Thread(target=the_count_incrementor)
thread_2 = threading.Thread(target=the_count_incrementor)
thread_3 = threading.Thread(target=the_count_incrementor)
# Start your threads
thread_1.start()
thread_2.start()
thread_3.start()
# Wait for the threads to finish... yalla...
thread_1.join()
thread_2.join()
thread_3.join()
print(f"The counter value is {the_counter}")
In this example, the increment_counter function increments the shared counter variable. The lock object is used to ensure that only one thread at a time can modify the shared resource, preventing data corruption or race conditions.
Summing up
Python's threading module offers a simple and powerful way to implement multithreading in your applications. By understanding the basic concepts and synchronisation techniques, you can create concurrent applications that are efficient and responsive.
The code examples provided in this article should be a pretty cool starting point for further exploration and experimentation with Python threading.
Check out the links below for useful background info on this topic.
Real Python: https://realpython.com/intro-to-python-threading/
Corey Schafer's YouTube Tutorial: https://www.youtube.com/watch?v=IEEhzQoKtQU
Python Concurrency: https://www.toptal.com/python/beginners-guide-to-concurrency-and-parallelism-in-python