Python Multithreading Example for Loop

Here’s an example of how you can use multithreading in Python to execute a for loop concurrently:

import threading

def my_function(item):
    # Do some processing with the item
    print(f"Processing item: {item}")

# List of items to process
items = [1, 2, 3, 4, 5]

# Create a lock to synchronize access to shared resources (optional)
lock = threading.Lock()

# Create a thread for each item and start them concurrently
threads = []
for item in items:
    thread = threading.Thread(target=my_function, args=(item,))

# Wait for all threads to finish
for thread in threads:

print("All threads have finished.")

In this example, my_function() represents the task you want to perform for each item in the loop. You can replace the print statement with your desired processing logic. Each thread executes this function with a different item from the list.

The threading.Thread class is used to create a new thread, passing the my_function as the target and the corresponding item as an argument using the args parameter.

The threads are then started using the start() method, and references to each thread are stored in a list.

Finally, the main thread waits for all the spawned threads to finish using the join() method, and once all the threads have finished their execution, the message “All threads have finished” is printed.

Note that the order of execution of the threads may vary due to the concurrent nature of multithreading.

How do I run two threads simultaneously in Python?

Yes, it is possible to run multiple threads simultaneously in Python using the threading module. The threading module provides a way to create and manage threads in Python.

Is it possible to do multithreading in Python?

Here’s an example that demonstrates running two threads simultaneously:

import threading

def thread_function1():
    print("Thread 1 is running")

def thread_function2():
    print("Thread 2 is running")

# Create thread objects
thread1 = threading.Thread(target=thread_function1)
thread2 = threading.Thread(target=thread_function2)

# Start the threads

# Wait for the threads to finish

print("All threads have finished")

In this example, we define two functions thread_function1 and thread_function2, which represent the tasks that we want to execute concurrently.

We create thread objects thread1 and thread2 using the threading.Thread class, specifying the corresponding target function for each thread.

To start the threads, we call the start() method on each thread object. This will initiate the execution of the target functions in separate threads.

After starting the threads, we use the join() method on each thread object to wait for them to finish. This ensures that the main thread waits until both threads have completed their execution.

Finally, we print the message “All threads have finished” to indicate that all threads have completed their tasks.

Note that the order of execution between the threads may vary, as it depends on the operating system’s scheduling.

Read More;

  • Yaryna Ostapchuk

    I am an enthusiastic learner and aspiring Python developer with expertise in Django and Flask. I pursued my education at Ivan Franko Lviv University, specializing in the Faculty of Physics. My skills encompass Python programming, backend development, and working with databases. I am well-versed in various computer software, including Ubuntu, Linux, MaximDL, LabView, C/C++, and Python, among others.

Leave a Comment