mutex lock
时间: 2023-08-28 08:04:58 浏览: 56
互斥锁(mutex lock)是一种常用的线程同步机制,用于保护共享资源的访问。在多线程环境下,当多个线程同时访问某个共享资源时,互斥锁可以确保同一时间只有一个线程可以访问该资源,避免数据竞争和不一致性的问题。
互斥锁有两种状态:锁定(locked)和未锁定(unlocked)。当线程想要访问共享资源时,它首先尝试获取互斥锁。如果状态是未锁定,线程可以获取锁,并将状态设置为锁定;如果状态是锁定,线程就会被阻塞,直到锁被释放。一旦线程完成对共享资源的访问,它会释放互斥锁,使得其他线程可以获取锁并访问资源。
以下是使用C/C++语言中pthread库提供的互斥锁的示例代码:
```c
#include <pthread.h>
// 定义互斥锁
pthread_mutex_t mutex;
// 共享资源
int shared_resource = 0;
void* thread_function(void* arg) {
// 获取互斥锁
pthread_mutex_lock(&mutex);
// 访问共享资源
shared_resource++;
// 释放互斥锁
pthread_mutex_unlock(&mutex);
return NULL;
}
int main() {
// 初始化互斥锁
pthread_mutex_init(&mutex, NULL);
// 创建多个线程
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, thread_function, NULL);
pthread_create(&thread2, NULL, thread_function, NULL);
// 等待线程结束
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
// 销毁互斥锁
pthread_mutex_destroy(&mutex);
return 0;
}
```
在上述示例中,两个线程同时访问 `shared_resource` 变量,并使用互斥锁确保了对该变量的原子操作,避免了竞态条件的问题。