[Linux operating system] Mutex locks in Linux system programming

1. The principle of mutual exclusion lock

In Linux system programming, a mutex (Mutex) is a synchronization mechanism used to protect shared resources. It can ensure that only one thread can access the protected resource at any time, thereby avoiding data competition and inconsistency caused by multiple threads modifying the resource at the same time.

The principle of a mutex is realized through a lock variable, which can be in two states: locked (locked) and unlocked (unlocked). When a thread wants to access a protected resource, it needs to try to acquire the lock first. If the lock is unlocked, the thread can acquire the lock and set the lock status to locked; if the lock is locked, the thread Need to wait until the lock is released.

2. Mutex-related functions

We can use the functions provided by the pthread library to implement the operation of the mutex. The following are some commonly used mutex functions:

  • pthread_mutex_init: Used to initialize mutex variables.
  • pthread_mutex_destroy: Used to destroy the mutex variable.
  • pthread_mutex_lock: Used to acquire a mutex.
  • pthread_mutex_unlock: Used to release the mutex.
  1. pthread_mutex_initThe role of the function is to initialize the mutex variable.

    • prototype:int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);
    • parameter:
      • mutex: Pointer to the mutex variable to be initialized.
      • attr: Pointer to the attribute of the mutex, usually set to NULL.
    • Return value: Returns 0 on success, returns an error code on failure.
  2. pthread_mutex_destroyThe role of the function is to destroy the mutex variable.

    • prototype:int pthread_mutex_destroy(pthread_mutex_t *mutex);
    • parameter:
      • mutex: Pointer to the mutex variable to be destroyed.
    • Return value: Returns 0 on success, returns an error code on failure.
  3. pthread_mutex_lockThe role of the function is to acquire a mutex.

    • prototype:int pthread_mutex_lock(pthread_mutex_t *mutex);
    • parameter:
      • mutex: Pointer to the mutex variable to acquire.
    • Return value: Returns 0 on success, returns an error code on failure.
  4. pthread_mutex_unlockThe role of the function is to release the mutex.

    • prototype:int pthread_mutex_unlock(pthread_mutex_t *mutex);
    • parameter:
      • mutex: Pointer to the mutex variable to be released.
    • Return value: Returns 0 on success, returns an error code on failure.

3. An example of a mutex

Let's use an example to illustrate how to use a mutex. Suppose we have a global variable count, and multiple threads need to accumulate it at the same time. Failure to use a mutex could result in multiple threads reading and modifying at the same time count, leading to incorrect results.

#include <stdio.h>
#include <pthread.h>

int count = 0;
pthread_mutex_t mutex;

void* thread_func(void* arg) {
    
    
    // 获取互斥锁
    pthread_mutex_lock(&mutex);

    // 对count进行累加操作
    for (int i = 0; i < 10000; i++) {
    
    
        count++;
    }

    // 释放互斥锁
    pthread_mutex_unlock(&mutex);

    pthread_exit(NULL);
}

int main() {
    
    
    // 初始化互斥锁
    pthread_mutex_init(&mutex, NULL);

    pthread_t threads[10];

    // 创建10个线程
    for (int i = 0; i < 10; i++) {
    
    
        pthread_create(&threads[i], NULL, thread_func, NULL);
    }

    // 等待所有线程结束
    for (int i = 0; i < 10; i++) {
    
    
        pthread_join(threads[i], NULL);
    }

    // 销毁互斥锁
    pthread_mutex_destroy(&mutex);

    printf("count = %d\n", count);

    return 0;
}

In the above code, we first pthread_mutex_initinitialized the mutex variable with the function mutex, then created 10 threads and set their execution function to thread_func. In the function, the mutex is thread_funcfirst obtained through the function, then the global variable is accumulated, and finally the mutex is released through the function. In the function, we use the function to wait for all threads to end, and then use the function to destroy the mutex variable.pthread_mutex_lockcountpthread_mutex_unlockmainpthread_joinpthread_mutex_destroy

Running the above code, we can get the correct result. Due to the existence of the mutex, each thread countwill first obtain the mutex when performing the accumulation operation on the pair, thus ensuring the atomicity and consistency of the operation.

Summarize

Through this article, we understand the principle and related functions of mutexes in Linux system programming. Mutex is a synchronization mechanism used to protect shared resources, which can avoid data competition and inconsistency caused by multiple threads modifying resources at the same time. We can use the functions provided by the pthread library to implement mutex operations, such as pthread_mutex_init, pthread_mutex_lock, pthread_mutex_unlockand so on.

insert image description here

Guess you like

Origin blog.csdn.net/Goforyouqp/article/details/132411646