Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
threads
synchronization
multithreading

How to synchronize threads in Python

Marvah Mushtaq

What is the threading library?

A library in Python called threading is used to work around threading and synchronization in Python.

import threading

We import the library as written above.

The library provides a simple-to-implement locking mechanism that allows us to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock.

Python threading allows us to have different parts of our program run concurrently and can simplify our design.

Code for synchronization

Below is the code for creating and synchronizing the threads.

#!/usr/bin/python
import threading
import time


class myThread (threading.Thread):
   def __init__(self, threadID, name, counter):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.counter = counter
   def run(self):
      print ("Starting " + self.name)

   # Get lock to synchronize threads
      threadLock.acquire()
      print_time(self.name, self.counter, 3)

      # Free lock to release next thread
      threadLock.release()
def print_time(threadName, delay, counter):
   while counter:
      time.sleep(delay)
      print ("%s: %s" % (threadName, time.ctime(time.time())))
      counter -= 1
      
threadLock = threading.Lock()
threads = []
# Create new threads
thread1 = myThread(1, "Thread_1", 1)
thread2 = myThread(2, "Thread_2", 2)
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for t in threads:
   t.join()
print ("Exiting Main Thread")

Explanation

  • In line 2, we import the threading library.

  • In lines 7-11, we define threads.

  • In lines 16-17, we get the lock to synchronize the threads.

  • In line 20, we release the lock so that the next thread can access it.

RELATED TAGS

python
threads
synchronization
multithreading

CONTRIBUTOR

Marvah Mushtaq
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring