Python multithreading example

Ken 53 Published: 08/26/2024

Python multithreading example

Here is an example of using multi-threading in Python:

import threading

import time

import random

class MyThread(threading.Thread):

def init(self, name):

super().init()

self.name = name

def run(self):

print(f"{self.name} started.")

for i in range(5):

Simulate some work

time.sleep(random.randint(1, 3))

print(f"{self.name} is working on iteration {i+1}")

print(f"{self.name} finished.")

if name == "main":

threads = []

for i in range(5):

thread_name = f"Thread-{i+1}"

t = MyThread(thread_name)

threads.append(t)

start_time = time.time()

for t in threads:

t.start()

for t in threads:

t.join()

end_time = time.time()

print(f"All threads finished. Total execution time: {end_time-start_time:.2f} seconds")

In this example, we create a class MyThread that inherits from the threading.Thread class. This allows us to define our own thread class and override its default behavior.

The run method is where the actual work of the thread takes place. In this case, it simulates some work by sleeping for a random amount of time (between 1-3 seconds) and then printing out a message indicating what it's doing.

In the main part of the script, we create five threads using our MyThread class. We store these in a list called threads. Then, we start all the threads at once by calling their start method. Finally, we wait for all the threads to finish by calling their join method.

When you run this script, you will see each thread's name followed by "started." and then it will print out messages indicating what it's doing as it works on its tasks. Once a thread is finished with its work, it will print out "finished." Finally, the script will print out when all the threads have finished.

The output of this script will look something like this:

Thread-1 started.

Thread-2 started.

Thread-3 started.

Thread-4 started.

Thread-5 started.

Thread-1 is working on iteration 1

Thread-2 is working on iteration 1

Thread-3 is working on iteration 1

Thread-4 is working on iteration 1

Thread-5 is working on iteration 1

... (this will repeat for each thread, showing that they are all doing their work concurrently)

Thread-1 finished.

Thread-2 finished.

Thread-3 finished.

Thread-4 finished.

Thread-5 finished.

All threads finished. Total execution time: 6.50 seconds

As you can see from the output, the threads do indeed run in parallel. Each thread takes a different amount of time to finish, depending on how much "work" it has to do.

I hope this example helps illustrate how multithreading works in Python! Let me know if you have any questions or if there's anything else I can help with.

Is Python single threaded or multi?

I'm glad you asked!

Python is a fascinating programming language, and its concurrency model is an essential aspect of its design.

The Answer:

Python is designed to be single-threaded by default, meaning that it runs your code on one thread at a time. This is because Python's Global Interpreter Lock (GIL) ensures that only one thread can execute instructions at any given moment.

In other words, when you write a Python program, it will always run on the main thread, and no other threads are executed concurrently by default.

But wait, there's more!

Python does provide some mechanisms to achieve concurrency, making it possible to run multiple tasks or threads simultaneously. Here are a few examples:

Multi-processing: The multiprocessing module allows you to create separate processes that can run independently of each other. Each process has its own thread and memory space. Threading: You can use the threading module to create additional threads within your Python program. These threads can execute concurrently, but be aware that they still share the same memory space as the main thread. Asyncio: The asyncio library provides support for asynchronous programming in Python. This allows you to write code that yields control back to the event loop at specific points, making it possible to run multiple tasks concurrently.

Why is this important?

When writing concurrent or parallel code in Python, understanding how threads and processes interact with each other can be crucial. For example:

When using multiprocessing, you need to ensure that data sharing between processes is properly handled. With threading, you should consider synchronization primitives (like locks) to coordinate access to shared resources.

By being aware of these nuances, you'll be better equipped to write efficient and effective concurrent code in Python.

In Conclusion:

While Python itself is single-threaded by default, the language provides various mechanisms to achieve concurrency. With multiprocessing, threading, and asyncio libraries, you can create parallel or concurrent tasks that run simultaneously, allowing for improved responsiveness, scalability, and performance in your Python applications.

I hope this clears up any misconceptions about Python's concurrency model!