search
HomeSystem TutorialLINUXDetailed explanation of Linux multi-thread synchronization mutex Mutex

Detailed explanation of Linux multi-thread synchronization mutex Mutex

Feb 11, 2024 pm 06:48 PM
linuxlinux tutoriallinux systemlinux commandshell scriptSynchronization mechanismembeddedlinuxGetting started with linuxlinux learning

Linux system is an operating system that supports concurrent execution of multi-tasks. It can run multiple processes at the same time, thereby improving system utilization and efficiency. However, if there are multiple threads in a process, and these threads need to share some data or resources, data inconsistency or resource competition may occur, leading to system errors or exceptions. In order to solve this problem, you need to use some synchronization mechanisms, such as semaphores, condition variables, mutexes, etc. Among them, the mutex is a relatively simple and effective synchronization mechanism. It allows a thread to lock shared data or resources when accessing them to prevent other threads from accessing them at the same time, thus ensuring thread safety. This article will explain in detail the method of synchronizing the mutex Mutex in Linux multi-threads, including the initialization, locking, unlocking and destruction of the mutex.

1. Initialization

Under Linux, the thread's mutex data type is pthread_mutex_t. Before use, it must be initialized:

For statically allocated mutexes, you can set it to PTHREAD_MUTEX_INITIALIZER, or call pthread_mutex_init.

For a dynamically allocated mutex, after applying for memory (malloc), it is initialized through pthread_mutex_init, and pthread_mutex_destroy needs to be called before releasing the memory (free).

prototype:

int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);

int pthread_mutex_destroy(pthread_mutex_t *mutex);

head File:

Return value: Returns 0 if successful, returns error number if error occurs.

Note: If you use the default attributes to initialize the mutex, just set attr to NULL. Other values ​​will be explained later.

2. Mutually exclusive operation:

To access shared resources, you need to lock the mutex. If the mutex is already locked, the calling thread will block until the mutex is unlocked. After completing the access to the shared resources, you need to Unlock the mutex.

Detailed explanation of Linux multi-thread synchronization mutex MutexLet’s talk about the locking function:

head File:

prototype:

int pthread_mutex_lock(pthread_mutex_t *mutex);

int pthread_mutex_trylock(pthread_mutex_t *mutex);

Return value: Returns 0 if successful, returns error number if error occurs.

Description: Let’s talk specifically about the trylock function. This function is a non-blocking calling mode. That is to say, if the mutex is not locked, the trylock function will lock the mutex and gain access to the shared resources; If the mutex is locked, the trylock function will not block waiting and directly return EBUSY, indicating that the shared resource is busy.

Let’s talk about the solution function:

head File:

Prototype: int pthread_mutex_unlock(pthread_mutex_t *mutex);

Return value: Returns 0 if successful, returns error number if error occurs.

\3. Deadlock:

Deadlock mainly occurs when there are multiple dependent locks, and it occurs when one thread tries to lock the mutex in the opposite order as another thread. How to avoid deadlock is something that should be paid special attention to when using mutexes. .

Generally speaking, there are several unwritten basic principles:

Be sure to obtain the lock before operating on shared resources.

Be sure to release the lock after completing the operation.

If there are multiple locks, if the acquisition sequence is ABC, the release sequence should also be ABC.

The thread should release the lock it acquired when it returns an error.

Example:

#include 
#include 
#include 
#include 
#include 

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int lock_var;
time_t end_time;
int sum;

void pthread1(void *arg);
void pthread2(void *arg);
void pthread3(void *arg);

int main(int argc, char *argv[])
{
pthread_t id1,id2,id3;
pthread_t mon_th_id;
int ret;
sum=10;

end_time = time(NULL) 10;
pthread_mutex_init(&mutex,NULL);
ret=pthread_create(&id1,NULL,(void *)pthread1, NULL);
if(ret!=0)
perror("pthread cread1");

ret=pthread_create(&id2,NULL,(void *)pthread2, NULL);
if(ret!=0)
perror("pthread cread2");

ret=pthread_create(&id3,NULL,(void *)pthread3, NULL);
if(ret!=0)
perror("pthread cread3");

pthread_join(id1,NULL);
pthread_join(id2,NULL);
pthread_join(id3,NULL);
exit(0);
}

void pthread1(void *arg)
{
int i;
while(time(NULL) if(pthread_mutex_lock(&mutex)!=0) //lock
{
perror("pthread_mutex_lock");
}
else
printf("pthread1:pthread1 lock the variablen");
for(i=0;iif(pthread_mutex_unlock(&mutex)!=0) //unlock
{
perror("pthread_mutex_unlock");
}
else
printf("pthread1:pthread1 unlock the variablen");
sleep(1);
}
}

void pthread2(void *arg)
{
int nolock=0;
int ret;
while(time(NULL) if(ret==EBUSY)
printf("pthread2:the variable is locked by pthread1n");
else{
if(ret!=0)
{
perror("pthread_mutex_trylock");
exit(1);
}
else
printf("pthread2:pthread2 got lock.The variable is %dn",lock_var);
if(pthread_mutex_unlock(&mutex)!=0)//unlock
{
perror("pthread_mutex_unlock");
}
else
printf("pthread2:pthread2 unlock the variablen");
}
sleep(1);
}
}



void pthread3(void *arg)
{/*
int nolock=0;
int ret;
while(time(NULL) if(ret==EBUSY)
printf("pthread3:the variable is locked by pthread1 or 2n");
else
{
if(ret!=0)
{
perror("pthread_mutex_trylock");
exit(1);
}
else
printf("pthread3:pthread3 got lock.The variable is %dn",lock_var);
if(pthread_mutex_unlock(&mutex)!=0)
{
perror("pthread_mutex_unlock");
}
else
printf("pthread3:pthread2 unlock the variablen");
}
sleep(3);
}*/
}

This article explains in detail the method of synchronizing the mutex Mutex in Linux multi-threads, including the initialization, locking, unlocking and destruction of the mutex. By understanding and mastering this knowledge, we can better use mutexes to achieve synchronization between multiple threads and improve the stability and efficiency of the system.

The above is the detailed content of Detailed explanation of Linux multi-thread synchronization mutex Mutex. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:良许Linux教程网. If there is any infringement, please contact admin@php.cn delete
What is AI? A Beginner's Guide for Linux UsersWhat is AI? A Beginner's Guide for Linux UsersMay 07, 2025 am 11:23 AM

Artificial Intelligence (AI) is a term that’s been buzzing around for a while now, from self-driving cars to voice assistants like Siri and Alexa, AI is becoming a part of our everyday lives. But what exactly is AI, and why should Linux users care ab

50 Essential Linux Commands for Beginners and SysAdmins50 Essential Linux Commands for Beginners and SysAdminsMay 07, 2025 am 11:12 AM

For someone new to Linux, using it can still feel challenging, even with user-friendly distributions like Ubuntu and Mint. While these distributions simplify many tasks, some manual configuration is often required, but fully harnessing the power of L

How to Set Up Your Linux System for AI DevelopmentHow to Set Up Your Linux System for AI DevelopmentMay 07, 2025 am 10:55 AM

In the previous article, we introduced the basics of AI and how it fits into the world of Linux. Now, it’s time to dive deeper and set up your Linux system to start building your first AI model. Whether you’re a complete beginner or have some exper

How to Install Kloxo Web Hosting Control Panel in LinuxHow to Install Kloxo Web Hosting Control Panel in LinuxMay 07, 2025 am 10:52 AM

If you’re looking to manage your server with ease, Kloxo is a great option, as it is free and open-source web hosting control panel that allows you to manage your server and websites with a simple, user-friendly interface. In this guide, we’ll walk

How to Move Files and Folders with Spaces in LinuxHow to Move Files and Folders with Spaces in LinuxMay 07, 2025 am 10:17 AM

If you’ve ever found yourself in a situation where you’re trying to move a bunch of files and folders, only to be stumped by spaces in the folder names, you’re not alone. Spaces in filenames or folder names can quickly become a frustrat

7 Best Linux Distros for KDE Plasma Fans in 20257 Best Linux Distros for KDE Plasma Fans in 2025May 07, 2025 am 10:06 AM

The KDE Plasma desktop is renowned for its sleek design, extensive customization options, and impressive performance. For users who appreciate a polished, modern interface with the flexibility to tweak every detail, Plasma is a dream come true. But w

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment