面试题答案
一键面试在Linux C语言多线程服务器编程中,互斥锁(mutex)有两种初始化方式:
- 静态初始化:对于静态分配的互斥锁,可以使用
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;
}
- 动态初始化:对于动态分配的互斥锁(例如在堆上分配),需要使用
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
函数来销毁动态初始化的互斥锁,以避免资源泄漏。静态初始化的互斥锁在其作用域结束时会自动清理。