The Wayback Machine - https://web.archive.org/web/20241005000046/https://www.geeksforgeeks.org/mutex-lock-for-linux-thread-synchronization/
Open In App

Mutex lock for Linux Thread Synchronization

Last Updated : 24 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite : Multithreading in C

Thread synchronization is defined as a mechanism which ensures that two or more concurrent processes or threads do not simultaneously execute some particular program segment known as a critical section. Processes’ access to critical section is controlled by using synchronization techniques. When one thread starts executing the critical section (a serialized segment of the program) the other thread should wait until the first thread finishes. If proper synchronization techniques are not applied, it may cause a race condition where the values of variables may be unpredictable and vary depending on the timings of context switches of the processes or threads.

Thread Synchronization Problems
An example code to study synchronization problems :




#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
  
pthread_t tid[2];
int counter;
  
void* trythis(void* arg)
{
    unsigned long i = 0;
    counter += 1;
    printf("\n Job %d has started\n", counter);
  
    for (i = 0; i < (0xFFFFFFFF); i++)
        ;
    printf("\n Job %d has finished\n", counter);
  
    return NULL;
}
  
int main(void)
{
    int i = 0;
    int error;
  
    while (i < 2) {
        error = pthread_create(&(tid[i]), NULL, &trythis;, NULL);
        if (error != 0)
            printf("\nThread can't be created : [%s]", strerror(error));
        i++;
    }
  
    pthread_join(tid[0], NULL);
    pthread_join(tid[1], NULL);
  
    return 0;
}


How to compile above program?
To compile a multithreaded program using gcc, we need to link it with the pthreads library. Following is the command used to compile the program.

gfg@ubuntu:~/$ gcc filename.c -lpthread

In this example, two threads(jobs) are created and in the start function of these threads, a counter is maintained to get the logs about job number which is started and when it is completed.

Output :

Job 1 has started
Job 2 has started
Job 2 has finished
Job 2 has finished

Problem: From the last two logs, one can see that the log ‘Job 2 has finished’ is repeated twice while no log for ‘Job 1 has finished’ is seen.

Why it has occurred ?
On observing closely and visualizing the execution of the code, we can see that :

  • The log ‘Job 2 has started’ is printed just after ‘Job 1 has Started’ so it can easily be concluded that while thread 1 was processing the scheduler scheduled the thread 2.
  • If we take the above assumption true then the value of the ‘counter’ variable got incremented again before job 1 got finished.
  • So, when Job 1 actually got finished, then the wrong value of counter produced the log ‘Job 2 has finished’ followed by the ‘Job 2 has finished’ for the actual job 2 or vice versa as it is dependent on scheduler.
  • So we see that its not the repetitive log but the wrong value of the ‘counter’ variable that is the problem.
  • The actual problem was the usage of the variable ‘counter’ by a second thread when the first thread was using or about to use it.
  • In other words, we can say that lack of synchronization between the threads while using the shared resource ‘counter’ caused the problems or in one word we can say that this problem happened due to ‘Synchronization problem’ between two threads.
  • How to solve it ?

    The most popular way of achieving thread synchronization is by using Mutexes.

    Mutex

    • A Mutex is a lock that we set before using a shared resource and release after using it.
    • When the lock is set, no other thread can access the locked region of code.
    • So we see that even if thread 2 is scheduled while thread 1 was not done accessing the shared resource and the code is locked by thread 1 using mutexes then thread 2 cannot even access that region of code.
    • So this ensures synchronized access of shared resources in the code.

    Working of a mutex

    1. Suppose one thread has locked a region of code using mutex and is executing that piece of code.
    2. Now if scheduler decides to do a context switch, then all the other threads which are ready to execute the same region are unblocked.
    3. Only one of all the threads would make it to the execution but if this thread tries to execute the same region of code that is already locked then it will again go to sleep.
    4. Context switch will take place again and again but no thread would be able to execute the locked region of code until the mutex lock over it is released.
    5. Mutex lock will only be released by the thread who locked it.
    6. So this ensures that once a thread has locked a piece of code then no other thread can execute the same region until it is unlocked by the thread who locked it.

    Hence, this system ensures synchronization among the threads while working on shared resources.

    A mutex is initialized and then a lock is achieved by calling the following two functions : The first function initializes a mutex and through second function any critical region in the code can be locked.

      1. int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr) : Creates a mutex, referenced by mutex, with attributes specified by attr. If attr is NULL, the default mutex attribute (NONRECURSIVE) is used.

        Returned value
        If successful, pthread_mutex_init() returns 0, and the state of the mutex becomes initialized and unlocked.
        If unsuccessful, pthread_mutex_init() returns -1.

      2. int pthread_mutex_lock(pthread_mutex_t *mutex) : Locks a mutex object, which identifies a mutex. If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it. When the mutex has the attribute of recursive, the use of the lock may be different. When this kind of mutex is locked multiple times by the same thread, then a count is incremented and no waiting thread is posted. The owning thread must call pthread_mutex_unlock() the same number of times to decrement the count to zero.

        Returned value
        If successful, pthread_mutex_lock() returns 0.
        If unsuccessful, pthread_mutex_lock() returns -1.

    The mutex can be unlocked and destroyed by calling following two functions :The first function releases the lock and the second function destroys the lock so that it cannot be used anywhere in future.

      1. int pthread_mutex_unlock(pthread_mutex_t *mutex) : Releases a mutex object. If one or more threads are waiting to lock the mutex, pthread_mutex_unlock() causes one of those threads to return from pthread_mutex_lock() with the mutex object acquired. If no threads are waiting for the mutex, the mutex unlocks with no current owner. When the mutex has the attribute of recursive the use of the lock may be different. When this kind of mutex is locked multiple times by the same thread, then unlock will decrement the count and no waiting thread is posted to continue running with the lock. If the count is decremented to zero, then the mutex is released and if any thread is waiting for it is posted.

        Returned value
        If successful, pthread_mutex_unlock() returns 0.
        If unsuccessful, pthread_mutex_unlock() returns -1

      2. int pthread_mutex_destroy(pthread_mutex_t *mutex) : Deletes a mutex object, which identifies a mutex. Mutexes are used to protect shared resources. mutex is set to an invalid value, but can be reinitialized using pthread_mutex_init().

        Returned value
        If successful, pthread_mutex_destroy() returns 0.
        If unsuccessful, pthread_mutex_destroy() returns -1.

    mutex
    An example to show how mutexes are used for thread synchronization




    #include <pthread.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
      
    pthread_t tid[2];
    int counter;
    pthread_mutex_t lock;
      
    void* trythis(void* arg)
    {
        pthread_mutex_lock(&lock;);
      
        unsigned long i = 0;
        counter += 1;
        printf("\n Job %d has started\n", counter);
      
        for (i = 0; i < (0xFFFFFFFF); i++)
            ;
      
        printf("\n Job %d has finished\n", counter);
      
        pthread_mutex_unlock(&lock;);
      
        return NULL;
    }
      
    int main(void)
    {
        int i = 0;
        int error;
      
        if (pthread_mutex_init(&lock;, NULL) != 0) {
            printf("\n mutex init has failed\n");
            return 1;
        }
      
        while (i < 2) {
            error = pthread_create(&(tid[i]),
                                   NULL,
                                   &trythis;, NULL);
            if (error != 0)
                printf("\nThread can't be created :[%s]",
                       strerror(error));
            i++;
        }
      
        pthread_join(tid[0], NULL);
        pthread_join(tid[1], NULL);
        pthread_mutex_destroy(&lock;);
      
        return 0;
    }

    
    

    In the above code:

    • A mutex is initialized in the beginning of the main function.
    • The same mutex is locked in the ‘trythis()’ function while using the shared resource ‘counter’.
    • At the end of the function ‘trythis()’ the same mutex is unlocked.
    • At the end of the main function when both the threads are done, the mutex is destroyed.

    Output :

    Job 1 started
    Job 1 finished
    Job 2 started
    Job 2 finished
    

    So this time the start and finish logs of both the jobs are present. So thread synchronization took place by the use of Mutex.

    References :
    Synchronization (computer science)
    Lock (computer science)



    Previous Article
    Next Article

Similar Reads

Print numbers in sequence using thread synchronization
The problem is to synchronize n number of threads using pthread library. The idea is take thread count and print 1 in first thread, print 2 in second thread, print 3 in third thread, ..... print n in nth thread and again repeat from thread 1 infinitely. Prerequisite : Multithreading Examples : Input : Thread count Output : 1 2 3 ... thread count 1
2 min read
How to Fix - Unable to Lock the Administration Directory – Kali Linux
Kali Linux is among the most famous OS for ethical hacking and pentesting. It contains all the necessary tools for pentesting and ethical hacking. Using Kali is not easy and every user has once encountered errors. In this article, we will see how to solve this particular problem using Kali Linux. What is Unable to lock the administration directory
5 min read
How do I lock a folder with htaccess file?
The .htaccess file stands for hypertext access which is known as a configuration file and is used by Apache-based web servers. A configuration file is simply a file that contains the initial programming or the configuration of the server. This file is important for us because it allows us to make the server behave in the way we want. It also allows
6 min read
How to fix ‘unable to acquire the dpkg frontend lock’ error in Ubuntu?
Encountering the "Unable to acquire the 'dpkg' frontend lock" error is a common issue on Linux systems, particularly on Ubuntu and other Debian-based distributions. This error typically occurs when a process locks the 'dpkg' (Debian Package Manager) during a system update or software installation. The good news is that the issue can be easily resol
6 min read
Difference Between Arch Linux and Kali Linux
Arch Linux is an open-source Linux-based Operating System that is freely available for use. It belongs to the Pacman-based Linux family. It is a light weighted OS for daily use and could even be used by professionals. It was first released in March 2002. It is a beginner-friendly Linux Operating System. Features of Arch Linux: Minimalist approach:
4 min read
Neofetch In Linux – Snap cool screenshots of your Linux
Neofetch is a fancy, highly customizable, and aesthetic command-line system information screenshot utility tool. Written in the Bash scripting language, it works inside a terminal window, on triggering up the command it by default displays the operating system, software, and hardware of your system on the right side of the column alongside an ASCII
4 min read
Exodus - Copy Linux Binaries From One Linux System
Exodus is an easy-to-implement program, that is used for bundling dependencies, and also helps to effectively copy Linux ELF binaries from one to another machine securely, and this is very handy when you don't have root access, also if there are issues in the availability of the packages in the Linux distribution, Commonly Server oriented distribut
3 min read
Basic CentOS Linux Commands in linux
CentOS is a free and open-source operating system that aims to provide a stable reliable, and community-supported platform for servers and other enterprise applications. In this article, we will be covering CentOS Linux basics commands and functions of CentOS and also we will look into the advanced commands. These CentOS commands allow you to manag
3 min read
Linux on Azure – Linux Distributions
Azure, the cloud computing platform from Microsoft, offers a playground for deploying and managing your Linux-based operating systems. Think of it as a canvas of boundless resources, security, and scalability, painted onto which you can unleash the boundless creativity and flexibility of Linux. This powerful synergy unlocks a world of opportunity,
10 min read
Linux Virtualization : Resource throttling using cgroups
In Linux Virtualization – Chroot Jail article, we discussed about kernel namespaces and process jailing. To understand this article, you may not need to read the earlier one, but I strongly suggest that you go through it once before diving into resource throttling. It should help tremendously in understanding what's going on. What are cgroups? cgro
9 min read
Kali Linux - Password Cracking Tool
Password cracking is a mechanism that is used in most of the parts of hacking. Exploitation uses it to exploit the applications by cracking their administrator or other account passwords, Information Gathering uses it when we have to get the social media or other accounts of the C.E.O. or other employees of the target organization, Wifi Hacking use
5 min read
XSS-Freak - XSS Scanner Fully Written in Kali Linux
XSS or Cross-Site Scripting is the most emerging security flaw in Web Applications. When the arbitrary or malicious JavaScript is executed by the web application then it is said to be an XSS Vulnerable Website. There are various XSS Scanners through which we can detect the XSS on the target domain. XSS-Freak is an XSS Scanner developed in the Pytho
3 min read
Tracing memory usage in Linux
Memory is a critical resource in computing because its usage affects the performance and stability of a system. It's necessary to trace the memory usage of the system in order to determine the program that consumes all CPU resources or the program that is responsible for slowing down the activities of the CPU. Tracing memory usage also becomes nece
3 min read
How to install and configure Docker on Arch-based Linux Distributions(Manjaro) ?
In this article, we are going to see how to install and configure Docker on Arch-based Linux Distributions. Docker is an open-source containerization platform used for building, running, and managing applications in an isolated environment. A container is isolated from another and bundles its software, libraries, and configuration files. Containers
2 min read
atrm command in Linux with examples
atrm command is used to remove the specified jobs. To remove a job, its job number is passed in the command. A user can only delete jobs that belong to him. Only superuser can delete any job even if that belongs to another user. Syntax: atrm [-V] job [job...] Options: -V : Used to print the version number atrm -V job : Job number of the job which i
1 min read
expand Command in LINUX with examples
Whenever you work with files in LINUX there can be a situation when you are stuck with a file containing many tabs and whatever you need to do with a file requires that file with no tabs but with spaces. In this situation, the task looks quite simple if you are dealing with a small file but what if the file you are dealing with is very big or you n
3 min read
Internal and External Commands in Linux
The UNIX system is command-based i.e things happen because of the commands that you key in. All UNIX commands are seldom more than four characters long. They are grouped into two categories: Internal Commands : Commands which are built into the shell. For all the shell built-in commands, execution of the same is fast in the sense that the shell doe
4 min read
Cool Custom Welcome Messages on Linux terminal
There is a Linux hack which can be used to display a custom message on the terminal every time we open it. This can be done by manipulating the .bashrc shell script. What is .bashrc ? It is a shell script that Bash runs whenever it is started interactively. You can put any command in that file that you could type at the command prompt. Steps on how
3 min read
Useful and time saving bash commands in Linux
There are many useful bash scripts that can make things easier. Many things can be done just using the terminal. Here is a list of some of such useful bash scripts through which we can do things that cannot be done manually. 1. Counting the number of files(or directory) in a given directory: Go to the directory in which you want to count the number
3 min read
rcp Command in Linux with examples
There comes a time while using LINUX when there is a need to copy some information stored in a file to another computer. This can be done simply using rcp command line utility . Obviously there exists some other methods to complete the above mentioned task which are more secure (like scp or rsync) but this command lets you do this in the simple way
4 min read
Process Control Commands in Unix/Linux
Process control commands in Unix are: bg - put suspended process into background fg - bring process into foreground jobs - list processes bg Command : bg is a process control command that resumes suspended process while keeping them running in the background. User can run a job in the background by adding a "&" symbol at the end of the command.
3 min read
Processes in Linux/Unix
A program/command when executed, a special instance is provided by the system to the process. This instance consists of all the services/resources that may be utilized by the process under execution. Whenever a command is issued in Unix/Linux, it creates/starts a new process. For example, pwd when issued which is used to list the current directory
6 min read
Sherlock - Hunt Username on Social Media Kali Linux Tool
Sherlock is a free and open-source tool available on GitHub. This tool is free you can download it from Github and can use it for free of cost. Sherlock is used to finding usernames on social media on 300 sites. As you know many users register themselves on social media platforms using their own name. Suppose we need to find someone on any social m
3 min read
fmt command in Linux with examples
fmt command in LINUX actually works as a formatter for simplifying and optimizing text files. Formatting of text files can also be done manually, but it can be really time-consuming when it comes to large text files, this is where fmt comes to rescue. fmt re-formats each paragraph in the file specified, writing to standard output. Here's the syntax
4 min read
unexpand command in Linux with Examples
To convert the leading spaces and tabs into tabs, there exists a command line utility called unexpand command. The unexpand command by default convert each spaces into tabs writing the produced output to the standard output. Here's the syntax of unexpand command : Syntax : $unexpand [OPTION]... [FILE]... where, OPTION refers to the options compatib
2 min read
File Timestamps - mtime, ctime and atime in Linux
Timestamps are records for the times in which actions are performed on files. A timestamp is useful because it keeps records of when a file was accessed, modified, or added. Linux's files have 3 timestamps recorded by the computer: Access timestamp (atime): which indicates the last time a file was accessed.Modified timestamp (mtime): which is the l
4 min read
TheSpeedX / TBomb - Call and SMS Bomber for Kali Linux
TBomb is a free and open-source tool available on GitHub which is used to perform call and SMS bombing on the target phone number. This is the best tool for performing pranks on someone. This tool is written in python, so you must have python installed in your kali linux operating system. This tool works with open-source intelligence APIs that's wh
2 min read
YetAnotherSMSBomber - SMS Bomber in kali linux
YetAnotherSMSBomber is a free and open-source tool available on GitHub. This tool doesn't take your phone number, you only have to enter the target phone number and the tool will do the rest of the work. You must ensure that you always install the latest version of YetAnotherSMSBomber from GitHub in order to not get stuck with the working of the to
2 min read
Run Levels in Linux
A run level is a state of init and the whole system defines what system services are operating. Run levels are identified by numbers. Runlevel is a mode or state in which a Linux system operates. It has a crucial role in the management of the Linux System. Whenever a LINUX system boot, firstly the init process is started which is actually responsib
5 min read
Gasmask – Information Gathering Tool in Kali Linux
Gasmask is a free and open-source tool available on Github. Gasmask is an Open Source Intelligence and Information Gathering Tool based on (OSINT). Gasmask is capable of doing everything almost you need for reconnaissance as per your need it can perform reconnaissance easily. Gasmask works as an open-source tool intelligence tool. It integrates wit
7 min read
Article Tags :