4-3 预装旋转栅门(Preloaded turnstile)

旋转栅门的一个好处是,它是一个多功能组件,可以用于各种解决方案。 但是一个缺点是它迫使线程顺序执行,这可能导致更多的不必要的上下文切换。

在可重复使用的屏障解决方案中,如果解锁旋转栅门的线程预先加载旋转栅门,并且有足够的信号让正确数量的线程通过,就可以简化解决方案。

在这里插入图片描述
初始化

osSemaphoreId_t sem_mutex;
sem_mutex = osSemaphoreNew(1, 1, NULL);

osSemaphoreId_t sem_turnstile;
sem_turnstile = osSemaphoreNew(1, 0, NULL);

osSemaphoreId_t sem_turnstile2;
sem_turnstile2 = osSemaphoreNew(1, 0, NULL);

int count = 0;

void critical_point()
{
	static int num = 0;
	num++;
	printf("num = %d \r\n", num);
}

线程

osSemaphoreAcquire(sem_mutex, osWaitForever);
count++;
if(count == 3)
{
	printf("rendezvous 1...\r\n");
	osSemaphoreRelease(sem_turnstile);  /* unlock 1 */	
	osSemaphoreRelease(sem_turnstile);  /* unlock 1 */	
	osSemaphoreRelease(sem_turnstile);  /* unlock 1 */	
}
osSemaphoreRelease(sem_mutex);

osSemaphoreAcquire(sem_turnstile, osWaitForever); /* 1 turnstile */

critical_point();

osSemaphoreAcquire(sem_mutex, osWaitForever);
count--;
if(count == 0)
{
	printf("rendezvous 2...\r\n");
	osSemaphoreRelease(sem_turnstile2);  /* unlock 2 */
	osSemaphoreRelease(sem_turnstile2);  /* unlock 2 */
	osSemaphoreRelease(sem_turnstile2);  /* unlock 2 */
}
osSemaphoreRelease(sem_mutex);

osSemaphoreAcquire(sem_turnstile2, osWaitForever); /* 2 turnstile */

可以将以上线程的代码重写为一个屏障对象
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值