MST

星途 面试题库

面试题:C语言中Linux多线程服务器里互斥锁的初始化方式

在Linux C语言多线程服务器编程中,简述互斥锁(mutex)有哪几种初始化方式,并写出相应的代码示例。
40.8万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

在Linux C语言多线程服务器编程中,互斥锁(mutex)有两种初始化方式:

  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");
    // 模拟一些工作
    sleep(1);
    printf("Thread leaving 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;
}
  1. 动态初始化:对于动态分配的互斥锁(例如在堆上分配),需要使用 pthread_mutex_init 函数进行初始化。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

pthread_mutex_t* mutex;

void* thread_function(void* arg) {
    // 加锁
    pthread_mutex_lock(mutex);
    printf("Thread entered critical section\n");
    // 模拟一些工作
    sleep(1);
    printf("Thread leaving critical section\n");
    // 解锁
    pthread_mutex_unlock(mutex);
    return NULL;
}

int main() {
    pthread_t thread;
    // 动态分配互斥锁
    mutex = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t));
    if (mutex == NULL) {
        perror("malloc");
        return 1;
    }
    // 动态初始化互斥锁
    if (pthread_mutex_init(mutex, NULL) != 0) {
        perror("pthread_mutex_init");
        free(mutex);
        return 1;
    }
    // 创建线程
    pthread_create(&thread, NULL, thread_function, NULL);
    // 等待线程结束
    pthread_join(thread, NULL);
    // 销毁互斥锁
    pthread_mutex_destroy(mutex);
    // 释放内存
    free(mutex);
    return 0;
}

注意,使用完互斥锁后,需要调用 pthread_mutex_destroy 函数来销毁动态初始化的互斥锁,以避免资源泄漏。静态初始化的互斥锁在其作用域结束时会自动清理。