在Linux中,互斥锁(mutex)是一种用于实现进程或线程间同步的机制,确保多个进程或线程不会同时访问共享资源。以下是使用互斥锁的基本步骤:
在使用互斥锁之前,需要先初始化它。可以使用pthread_mutex_init
函数来初始化一个互斥锁。
#include <pthread.h>
pthread_mutex_t mutex;
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);
mutex
:指向要初始化的互斥锁。attr
:指向互斥锁属性的指针,通常设置为NULL
以使用默认属性。在访问共享资源之前,需要先对互斥锁进行加锁操作。可以使用pthread_mutex_lock
函数来实现。
int pthread_mutex_lock(pthread_mutex_t *mutex);
mutex
:指向要加锁的互斥锁。在访问完共享资源之后,需要释放互斥锁。可以使用pthread_mutex_unlock
函数来实现。
int pthread_mutex_unlock(pthread_mutex_t *mutex);
mutex
:指向要解锁的互斥锁。在不再需要使用互斥锁时,应该销毁它以释放相关资源。可以使用pthread_mutex_destroy
函数来销毁一个互斥锁。
int pthread_mutex_destroy(pthread_mutex_t *mutex);
mutex
:指向要销毁的互斥锁。以下是一个简单的示例,展示了如何使用互斥锁来保护共享资源:
#include <stdio.h>
#include <pthread.h>
#define NUM_THREADS 5
int shared_resource = 0;
pthread_mutex_t mutex;
void* thread_func(void* arg) {
int thread_id = *(int*)arg;
// 加锁
pthread_mutex_lock(&mutex);
// 访问共享资源
shared_resource++;
printf("Thread %d: shared_resource = %d\n", thread_id, shared_resource);
// 解锁
pthread_mutex_unlock(&mutex);
return NULL;
}
int main() {
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS];
// 初始化互斥锁
if (pthread_mutex_init(&mutex, NULL) != 0) {
perror("pthread_mutex_init");
return 1;
}
// 创建线程
for (int i = 0; i < NUM_THREADS; i++) {
thread_ids[i] = i;
if (pthread_create(&threads[i], NULL, thread_func, &thread_ids[i]) != 0) {
perror("pthread_create");
return 1;
}
}
// 等待线程结束
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
// 销毁互斥锁
pthread_mutex_destroy(&mutex);
return 0;
}
在这个示例中,多个线程并发地访问共享资源shared_resource
,通过互斥锁确保每次只有一个线程可以访问该资源。
通过以上步骤和示例代码,你可以有效地使用互斥锁来实现进程或线程间的同步。