c语言原子锁
时间: 2023-07-02 17:10:48 浏览: 124
在 C 语言中,原子锁可以使用互斥锁(mutex)来实现。互斥锁是一种同步机制,它可以确保同时只有一个线程访问共享资源,从而避免竞态条件(race condition)的问题。
下面是一个使用互斥锁实现原子锁的示例代码:
```
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t lock;
void atomic_increment(int *value) {
pthread_mutex_lock(&lock);
(*value)++;
pthread_mutex_unlock(&lock);
}
int main() {
int count = 0;
// 初始化互斥锁
pthread_mutex_init(&lock, NULL);
// 并发执行 1000 次原子递增操作
pthread_t threads[1000];
for (int i = 0; i < 1000; i++) {
pthread_create(&threads[i], NULL, (void *(*)(void *)) atomic_increment, &count);
}
for (int i = 0; i < 1000; i++) {
pthread_join(threads[i], NULL);
}
// 输出结果
printf("count = %d\n", count);
// 销毁互斥锁
pthread_mutex_destroy(&lock);
return 0;
}
```
在上面的代码中,我们使用了 pthread 库提供的互斥锁来保证原子性。在 `atomic_increment()` 函数中,我们首先使用 `pthread_mutex_lock()` 函数来获取锁,然后执行递增操作,最后使用 `pthread_mutex_unlock()` 函数来释放锁。这样,每次只有一个线程能够获取到锁,从而避免了竞态条件的问题。