Home >System Tutorial >LINUX >Linux multi-thread mutex: a thread-safe synchronization mechanism

Linux multi-thread mutex: a thread-safe synchronization mechanism

PHPz
PHPzforward
2024-02-13 13:40:17469browse

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 introduce the mutual exclusion method of multi-threaded mutex in Linux system, including the initialization, locking, unlocking and destruction of mutex.

Synchronize

Multiple threads in the same process share the memory resources of the process. When multiple threads access the same shared resource at the same time, they need to coordinate with each other to avoid problems such as data inconsistency and overwriting. The coordination and communication between threads is called thread synchronization problem. The idea of ​​thread synchronization is to let multiple threads access shared resources in sequence instead of in parallel

Mutual Exclusion VS Synchronization

  • Mutual exclusion: means that a certain resource allows only one visitor to access it at the same time, and is unique and exclusive. But mutual exclusion cannot limit the order in which visitors access resources, that is, access is unordered. If the operation is an atomic operation, it is naturally mutually exclusive
  • Synchronization: refers to the orderly access of resources by visitors through other mechanisms on the basis of mutual exclusion (in most cases). In most cases, synchronization already implements mutual exclusion, especially when all writes to resources must be mutually exclusive. In a few cases, multiple visitors can be allowed to access resources at the same time

Mutex:

  • Essentially, it is a lock that provides exclusive access to resources, so the main function of Mutex is for mutual exclusion. A mutex allows only one thread to access data at the same time, and can be regarded as a 0/1 semaphore
  • The values ​​of Mutex objects are only 0 and 1. Represent the lock state and idle state of Mutex respectively:
    • Lock status: The current object is locked. If the user process/thread attempts to lock critical resources, it will enter waiting;
    • Idle state: The current object is idle, the user process/thread can lock critical resources, and then the Mutex value decreases by 1 and becomes 0.
  • Mutex can have an initial value when it is created, indicating whether the Mutex is in a locked state or an idle state after it is created.
  • In the same thread, in order to prevent deadlock, the system does not allow the Mutex to be locked twice in a row (the system usually returns immediately after the second call). In other words, the two corresponding operations of locking and unlocking need to be completed in the same thread.

Mutex model

#include 
pthread_mutex_t  mutex                //定义互斥锁               
pthread_mutex_init()            //初始化锁          
pthread_mutex_lock()/pthread_mutex_trylock()  ...     //加锁                  
pthread_mutex_unlock()          //解锁                        
pthread_mutex_destroy()         //销毁                        
//成功返回0,失败返回error number
#include 
int pthread_mutex_init  (pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr);
int pthread_mutex_lock  (pthread_mutex_t *mutex);
int pthread_mutex_trylock   (pthread_mutex_t *mutex);
int pthread_mutex_unlock    (pthread_mutex_t *mutex);
int pthread_mutex_destroy   (pthread_mutex_t *mutex);

deadlockdeadlock

Deadlock mainly occurs when there are multiple dependent locks, and it occurs when one thread tries to lock the mutex in the opposite order with another thread
When the Black Ball thread uses shared resources in the direction of A->, and the white ball thread uses shared resources in the order of B->A, unfortunately, the Black Ball thread locks A The resource waits until it obtains the released resource B, and the white ball thread locks resource B until it obtains the released resource A. The final result is that they cannot obtain the resources they want, and they all lock the resources the other party wants
Linux multi-thread mutex: a thread-safe synchronization mechanism

解决死锁:

  • 对共享资源操作前一定要获得锁
  • 完成操作后一定要释放锁
  • 尽量短的时间占用锁
  • 如果有多锁,如获得的顺序是ABC顺序,那么释放顺序也该是ABC
  • 线程错误返回时会释放它所获得的锁

例子

#include
#include
#include
#include

char* buf[5];
int pos;
//1.定义互斥量
pthread_mutex_t mutex;
void* task(void* pv){
    //3.使用互斥量进行加锁
    pthread_mutex_lock(&mutex);
    
    //4.访问共享内存
    buf[pos]=(char*)pv;
    sleep(1);
    pos++;

    //5.使用互斥量进行解锁
    pthread_mutex_unlock(&mutex);
}
main(){
    //2.初始化互斥量
    pthread_mutex_init(&mutex,NULL);

    pthread_t thread;
    pthread_create(&thread,NULL,task,(void*)"zhangfei");
    pthread_t thread2;
    pthread_create(&thread2,NULL,task,(void*)"guanyu");
    
    pthread_join(thread,NULL);
    pthread_join(thread2,NULL);

    //打印字符指针数组中的有效数据
    int i=0;
    for(i=0;iprintf("%s ",buf[i]);
    }
    printf("\n");
    //6.如果不再使用则销毁互斥量
    pthread_mutex_destroy(&mutex);
    return 0;
}

本文介绍了Linux系统中多线程互斥量的互斥的方法,包括互斥量的初始化、加锁、解锁和销毁等方面。通过了解和掌握这些知识,我们可以更好地使用互斥量来实现多线程之间的同步,提高系统的稳定性和效率。当然,Linux系统中多线程互斥量还有很多其他的特性和用法,需要我们不断地学习和研究。希望本文能给你带来一些启发和帮助。

The above is the detailed content of Linux multi-thread mutex: a thread-safe synchronization mechanism. 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