Home  >  Article  >  System Tutorial  >  Detailed explanation of Linux multi-thread synchronization mutex Mutex

Detailed explanation of Linux multi-thread synchronization mutex Mutex

王林
王林forward
2024-02-11 18:48:33847browse

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:lxlinux.net. If there is any infringement, please contact admin@php.cn delete