Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024

Thread Synchronization

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Threads can be considered lightweight processes. Multithreading requires running two or more threads simultaneously to improve the system's performance. Thus, in multithreading, multiple threads execute concurrently. This helps our computer to perform various tasks at the same time.

Imagine a scenario where multiple threads have to modify/use some particular program section. For example, multiple threads want to write to the same file. One thread starts writing to a file, and simultaneously, another thread also starts writing to the same file. This will corrupt the data and ruin the entire purpose of the program.

Thus, we have seen that we can’t achieve total parallelism, and we need thread synchronization to coordinate between multiple threads. Thread Synchronization is a process to ensure that only one thread uses a critical resource at a time. 

Methods of thread synchronization

There are various methods to handle thread synchronization. These methods can be divided into four categories:

  1. Blocking methods
  2. Locking constructs
  3. No blocking synchronization
  4. Signaling

Blocking Methods

These are the methods where one thread waits for another to finish execution for some time. Here, the execution of one process is blocked, hence the name blocking method. The following are some of the blocking methods:

  1. Sleep: It stops the execution of one thread for a defined time. For example - thread.sleep(100).
  2. Join: In join, we do not have to pre-define the time of blocking. It pauses the calling thread till the joined threads have completed execution. For example - thread.join().
  3. Wait: It allows the calling thread to stop executing until the current thread has completed execution. Example: thread.wait().

Locking Methods

Locking is a method of thread synchronization that limits the access of a resource in multiple threads. It allows only one thread at a time to enter the locked area. The following are some of the locking methods:

  1. Lock: A lock is applied before starting the critical section of the code. When one thread enters the critical section, it acquires the lock. Now no other thread can enter this section. Once the first thread has finished executing the critical section, it releases the lock, and the following thread can now enter this section.
  2. Mutex: Mutual Exclusion (Mutex) ensures that a particular section of code is executed only once at one time. 

Example

Try to guess the output of the below python code:

import threading

# Function to print numbers from 0 to N
def fun(n):
    for i in range (n):
        print("Current value of i: ", i)

lock = threading.Lock()

# Creating two threads and calling fun with argument as 5
t1 = threading.Thread(target = fun, args=(5, ))
t2 = threading.Thread(target = fun, args=(5, ))

# Starting both threads
t1.start()
t2.start()

# Joining both threads
t1.join()
t2.join()

Output:

Current value of i:  Current value of i:  00
Current value of i: Current value of i:   1
1Current value of i:
 Current value of i: 2
2Current value of i:
 Current value of i: 3 3
Current value of i: Current value of i:   44

Explanation: We can see that the output is completely messed up. This has happened because both threads used the function ‘fun’ simultaneously. And since we were printing inside the function, the print statements of both the threads were executed simultaneously and messed up the output.

Now try to guess the output of the following python code:

import threading

# Function to print numbers from 0 to N
def fun(n):
    lock.acquire()
    for i in range (n):
        print("Current value of i: ", i)
    lock.release()

lock = threading.Lock()

# Creating two threads and calling fun with argument as 10
t1 = threading.Thread(target = fun, args=(5, ))
t2 = threading.Thread(target = fun, args=(5, ))

# Starting both threads
t1.start()
t2.start()

# Joining both threads
t1.join()
t2.join()

Output:

Current value of i:  0
Current value of i:  1
Current value of i:  2
Current value of i:  3
Current value of i:  4
Current value of i:  0
Current value of i:  1
Current value of i:  2
Current value of i:  3
Current value of i:  4

Explanation: This time, we have used lock before the for loop. When one thread enters this area, it will acquire the lock and execute the for loop. The other thread will have to wait until the lock is released. Thus, we get a clean output.

Must Read: Multithreading in C#, Multithreading in Python

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Advantages of thread synchronization

  1. Thread synchronization ensures that only one thread accesses the critical section of the code at a time.
  2. It ensures fair allocation of resources to the threads.
  3. It helps to complete the requests in a specific order.
  4. Thread synchronization ensures that no thread has infinite waiting time.

FAQs

  1. What is thread synchronization?
    Thread Synchronization is a process to ensure that only one thread uses a critical resource at a time. It provides a safe method for multiple threads to execute concurrently.
  2. What are Blocking methods in thread synchronization?
    These are the methods where one thread waits for another to finish execution for some time. Here, the execution of one process is blocked, hence the name blocking method. Sleep and Join are the two most common blocking methods.
  3. What are Locking methods in thread synchronization?
    Locking is a method of thread synchronization that limits the access of a resource in multiple threads. It allows only one thread at a time to enter the locked area. Lock and Mutex are the two most common locking methods.

Key Takeaways

In this article, we learned about thread synchronization. We saw the need for thread synchronization and different ways to achieve it. We also looked at an example using multiple threads with and without thread synchronization. 

We hope that this blog has helped you enhance your knowledge of thread synchronization and if you would like to learn more, check out our articles on Coding Ninjas Studio. Do upvote our blog to help other ninjas grow. Happy Coding!

Topics covered
1.
Introduction
2.
Methods of thread synchronization
2.1.
Blocking Methods
2.2.
Locking Methods
2.3.
Example
3.
Advantages of thread synchronization
4.
FAQs
5.
Key Takeaways