📜  计数和二进制信号量之间的区别

📅  最后修改于: 2021-09-16 10:22:33             🧑  作者: Mango

先决条件:进程同步中的信号量
概述

信号量是一个整数变量,可用于解决各种同步问题。它强加了有意的约束,以帮助程序员避免错误。此外,它使解决方案更有条理,使程序可移植和高效。它只能通过两个标准的原子操作来访问:wait() 和 signal()。实体是尝试访问共享资源的实体。实体可以是进程或线程。在本文中,术语进程和线程可互换更改。

有一些要求可以保证同步,它们是:

  • 互斥
  • 进步
  • 有界等待

根据计数器的范围,信号量可以分为两部分,一是计数信号量,二二进制信号量。

1. 二进制信号量:

  1. 二进制信号量是整数值范围在 0 和 1 之间的信号量。
  2. 它什么都不是,但类似于锁,有两个值:0 和 1。这里 0 表示忙,而 1 表示空闲。
  3. 使用二进制信号量背后的想法是,它一次只允许一个进程进入临界区(从而允许它访问共享资源)。
  4. 这里,0 表示一个进程或线程处于临界区(即它正在访问共享资源),而另一个进程或线程应该等待它完成。另一方面,1 表示没有进程正在访问共享资源,并且临界区是空闲的。
  5. 它保证互斥,因为在任何时间点都不能有两个进程处于临界区。
  6. 由于它只是一个保存整数值的变量,因此不能保证有界等待。可能会发生一个进程可能永远没有机会进入临界区,这可能导致它的饥饿。我们不希望那样。

2. 计数信号量:

  1. 计数信号量是具有多个计数器值的信号量。该值的范围可以是不受限制的域。
  2. 它是一种结构,它包含一个变量,称为信号量变量,可以采用两个以上的值和一个任务或实体列表,它只是进程或线程。
  3. semaphore 变量的值是临界区中允许的进程或线程数。
  4. 计数信号量的值可以在 0 到 N 之间,其中 N 是可以自由进入和退出临界区的进程数。
  5. 如前所述,计数信号量可以允许多个进程或线程访问临界区,因此不能保证互斥。
  6. 由于进程的多个实例可以随时访问共享资源,计数信号量保证了有界等待。使用这样的信号量,进入临界区的进程必须等待另一个进程进入临界区,这意味着没有进程会饿死。

使用这两个信号量,进程能够进入临界区,从而取得进展。

计数和二进制信号量之间的区别:

Criteria

Binary Semaphore

Counting Semaphore

Definition A Binary Semaphore is a semaphore whose integer value range over 0 and 1. A counting semaphore is a semaphore that has multiple values of the counter. The value can range over an unrestricted domain.
Structure Implementation typedef struct {
      int semaphore_variable;
}binary_semaphore;
typedef struct {      
        int semaphore_variable;
        Queue list;                                                   //A queue to store the list of task
      }counting_semaphore;
Representation 0 means that a process or a thread is accessing the critical section, other process should wait for it to exit the critical section. 1 represents the critical section is free. The value can range from 0 to N, where N is the number of process or thread that has to enter the critical section. 
Mutual Exclusion Yes, it guarantees mutual exclusion, since just one process or thread can enter the critical section at a time. No, it doesn’t guarantees mutual exclusion, since more than one process or thread can enter the critical section at a time.
Bounded wait No, it doesn’t guarantees bounded wait, as only one process can enter the critical section, and there is no limit on how long the process can exist in the critical section, making another process to starve. Yes, it guarantees bounded wait, since it maintains a list of all the process or threads, using a queue, and each process or thread get a chance to enter the critical section once. So no question of starvation.