MST

星途 面试题库

面试题:C语言中Linux互斥锁的初始化方式

在Linux环境下,使用C语言编程,简述互斥锁有哪几种初始化方式,并给出相应的代码示例。
28.6万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

互斥锁在Linux环境下C语言编程中有两种初始化方式:

  1. 静态初始化: 适用于互斥锁对象在编译时就确定的情况,使用PTHREAD_MUTEX_INITIALIZER宏。
    #include <pthread.h>
    #include <stdio.h>
    
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    
    void* thread_function(void* arg) {
        pthread_mutex_lock(&mutex);
        printf("Thread entered critical section\n");
        // 临界区代码
        pthread_mutex_unlock(&mutex);
        return NULL;
    }
    
    int main() {
        pthread_t thread;
        pthread_create(&thread, NULL, thread_function, NULL);
        pthread_join(thread, NULL);
        return 0;
    }
    
  2. 动态初始化: 适用于需要在运行时确定互斥锁属性等情况,使用pthread_mutex_init函数。
    #include <pthread.h>
    #include <stdio.h>
    
    pthread_mutex_t mutex;
    
    void* thread_function(void* arg) {
        pthread_mutex_lock(&mutex);
        printf("Thread entered critical section\n");
        // 临界区代码
        pthread_mutex_unlock(&mutex);
        return NULL;
    }
    
    int main() {
        pthread_t thread;
        pthread_mutex_init(&mutex, NULL);
        pthread_create(&thread, NULL, thread_function, NULL);
        pthread_join(thread, NULL);
        pthread_mutex_destroy(&mutex);
        return 0;
    }
    

在动态初始化时,需要注意在不再使用互斥锁后调用pthread_mutex_destroy函数来释放相关资源。