ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 自旋锁 - 自旋锁也是一种多线程同步的变量 - 使用自旋锁的线程会反复检査锁变量是否可用 - 自旋锁不会让出CPU,是一种忙等待状态 - **死循环等待锁被释放** **优点** - 自旋锁避免了进程或线程上下文切换的开销 - 操作系统内部很多地方使用的是自旋锁 - 自旋锁**不适合在单核CPU**使用 API 是 `pthread_spinlock_t` ## 示例 <details> <summary>main.cpp</summary> ``` #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <vector> 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; } ``` </details> <br /> 编译 ``` g++ main.cpp -lpthread ./a.out ```