自旋锁
最后更新于:2022-04-02 04:06:19
[TOC]
## 自旋锁
- 自旋锁也是一种多线程同步的变量
- 使用自旋锁的线程会反复检査锁变量是否可用
- 自旋锁不会让出CPU,是一种忙等待状态
- **死循环等待锁被释放**
**优点**
- 自旋锁避免了进程或线程上下文切换的开销
- 操作系统内部很多地方使用的是自旋锁
- 自旋锁**不适合在单核CPU**使用
API 是 `pthread_spinlock_t`
## 示例
#include
#include
#include
#include
pthread_spinlock_t spin_lock;
int num =0;
void *producer(void*){
int times = 10000000;
while(times--){
pthread_spin_lock(&spin_lock);
num++;
pthread_spin_unlock(&spin_lock);
}
}
void *comsumer(void*){
int times = 10000000;
while(times--){
pthread_spin_lock(&spin_lock);
num--;
pthread_spin_unlock(&spin_lock);
}
}
int main(){
printf("stat in main function.");
pthread_spin_init(&spin_lock,0);
pthread_t thread1,thread2;
pthread_create(&thread1,NULL,&producer,NULL);
pthread_create(&thread2,NULL,&comsumer,NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
printf("print in main function:num=%d",num);
return 0;
}
```
编译 ``` g++ main.cpp -lpthread ./a.out ```
';
main.cpp
``` #include编译 ``` g++ main.cpp -lpthread ./a.out ```