个性化阅读
专注于IT技术分析

二进制信号量或互斥量

在计算信号量时, 未提供互斥, 因为我们拥有在关键部分同时执行的一组线程。

但是, Binary Semaphore严格提供互斥。在这里, 关键部分中最多只能有1个进程, 而不是关键部分中有1个以上的可用插槽。信号量只能有两个值, 即0或1。

让我们看一下二进制信号量的编程实现。

StructBsemaphore
{
	enum Value(0, 1); //value is enumerated data type which can only have two values 0 or 1.
	Queue type L;
}
/* L contains all PCBs corresponding to process 
Blocked while processing down operation unsuccessfully. 
*/ 
Down (Bsemaphore S) 
{
	if (s.value == 1) // if a slot is available in the 
	//critical section then let the process enter in the queue. 
	{
		S.value = 0; // initialize the value to 0 so that no other process can read it as 1. 
	}
	else
	{
		put the process (PCB) in S.L; //if no slot is available 
		//then let the process wait in the blocked queue. 
		sleep(); 
	}
}
Up (Bsemaphore S) 
{
	if (S.L is empty) //an empty blocked processes list implies that no process 
	//has ever tried to get enter in the critical section. 
	{
		S.Value =1; 
	}
	else
	{
		Select a process from S.L; 
		Wakeup(); // if it is not empty then wake the first process of the blocked queue. 
	} 
}
赞(0)
未经允许不得转载:srcmini » 二进制信号量或互斥量

评论 抢沙发

评论前必须登录!