在Linux中,互斥锁(mutex)是一种用于实现进程间或线程间同步的机制,确保多个进程或线程不会同时访问共享资源。以下是互斥锁的使用指南:
首先,你需要包含相关的头文件:
#include <pthread.h>
定义一个互斥锁变量:
pthread_mutex_t mutex;
在使用互斥锁之前,必须对其进行初始化。可以使用pthread_mutex_init
函数:
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);
通常情况下,你可以使用默认属性:
pthread_mutex_init(&mutex, NULL);
在使用共享资源之前,调用pthread_mutex_lock
函数进行加锁:
int pthread_mutex_lock(pthread_mutex_t *mutex);
使用完共享资源后,调用pthread_mutex_unlock
函数进行解锁:
int pthread_mutex_unlock(pthread_mutex_t *mutex);
当不再需要互斥锁时,应该调用pthread_mutex_destroy
函数进行销毁:
int pthread_mutex_destroy(pthread_mutex_t *mutex);
以下是一个简单的示例,展示了如何使用互斥锁来保护共享资源:
#include <stdio.h>
#include <pthread.h>
#define NUM_THREADS 5
int shared_resource = 0;
pthread_mutex_t mutex;
void* increment_resource(void* thread_id) {
long tid = (long)thread_id;
// 加锁
pthread_mutex_lock(&mutex);
// 访问共享资源
shared_resource++;
printf("Thread %ld: shared_resource = %d\n", tid, shared_resource);
// 解锁
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
int rc;
long t;
// 初始化互斥锁
if (pthread_mutex_init(&mutex, NULL) != 0) {
printf("Mutex initialization failed\n");
return 1;
}
// 创建线程
for (t = 0; t < NUM_THREADS; t++) {
rc = pthread_create(&threads[t], NULL, increment_resource, (void*)t);
if (rc) {
printf("Error creating thread %ld\n", t);
return 1;
}
}
// 等待线程结束
for (t = 0; t < NUM_THREADS; t++) {
pthread_join(threads[t], NULL);
}
// 销毁互斥锁
pthread_mutex_destroy(&mutex);
printf("Final value of shared_resource: %d\n", shared_resource);
return 0;
}
pthread_mutexattr_settype
设置属性为PTHREAD_MUTEX_RECURSIVE
)。通过遵循这些指南,你可以有效地使用互斥锁来保护共享资源,确保多线程程序的正确性和可靠性。