操作系统:17、线程同步之自旋锁
自旋锁
- 自旋锁是一种多线程同步的变量;
- 使用自旋锁的线程会反复检查锁变量是否可用,如果不可用会一直循环反复检查;
- 自旋锁不会让出CPU,是一种忙等待状态;
- 自旋锁是一种死循环等待锁被释放;
自旋锁的优势
- 自旋锁避免了进程或线程上下文切换的开销;
- 操作系统内部很多地方使用的是自旋锁;
- 自旋锁不适合在单核CPU使用;(因为自旋锁在等待时不会释放CPU,而是死循环去等待,若在单核cpu使用会占满cpu,引起其他进程或线程没有办法执行)
c提供的自旋锁api是pthread_spinlock_t。
自旋锁例子:
#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 = 100000000;
while(times --){
pthread_spin_lock(&spin_lock);//自旋锁加锁
num += 1;
pthread_spin_unlock(&spin_lock);//自旋锁解锁
}
}
//消费者
void *comsumer(void*){
int times = 100000000;
while(times --){
pthread_spin_lock(&spin_lock);//自旋锁加锁
num -= 1;
pthread_spin_unlock(&spin_lock);//自旋锁解锁
}
}
int main(){
printf("Start in main function.");
//初始化自旋锁
pthread_spin_init(&spin_lock, 0);
//创建线程1和线程2
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, &producer, NULL);//线程1执行生产者逻辑
pthread_create(&thread2, NULL, &comsumer, NULL);//线程2执行消费者逻辑
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Print in main function: num=%d\n", num);
return 0;
}
自旋锁占用完cpu的展示
1、将上访自旋锁例子改写一下,在消费者中执行等待10秒。
2、使用后台进程运行例子
3、查看进程占用cpu情况
可以看到进程使用cpu为99%,这就说明自旋锁在运行时并不会让出cpu。这就是自旋锁和互斥量最大不一样的地方。