操作系统:17、线程同步之自旋锁

操作系统: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。这就是自旋锁和互斥量最大不一样的地方。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值