2016-12-16 53 views
-1

根信号执行一般信号量实现并采用二进制信号:使用二进制信号

click image please, gen semaphore implemented using binary semaphores

所以我无法理解为什么我们需要进入信号,我可以看到它是如何工作正常,没有它。 多个进程如何进入临界区?第一个进程进入后,它等待(互斥),这意味着没有其他人可以进入,此外还有其他进程正在等待信号(互斥)

一般信号量可以允许多个进程进入关键部分区域,但我不明白在这段代码中是如何完成的。

+0

为什么会投票,我不会说得太好,请编辑一下,如果需要的话 – JessicaRam

+0

首先不要张贴图片的代码。 – EOF

+0

'entry'信号量可以防止多个进程同时等待'delay'信号量。还可以防止'c'低于'-1'。 – user3386109

回答

0

看到你的问题图像后,入口信号量的目的是只允许单个进程/线程等待锁定,如果你不使用它,其他进程将进入等待队列。

为什么我们需要进入信号

  • 进入信号不与任何值初始化,如果它是全局声明,然后它会与0所以,如果进入信号为0,等待初始化(进入)将只允许单个进程进入,因为wait()函数检查入口值是否小于零,那么进程将进入等待队列。

多个进程如何进入临界区?

  • 一次只能有一个进程处于关键部分 - 否则关键部分是什么?

  • 关键部分是访问共享变量 并且必须作为原子动作执行的代码段。这意味着在合作进程的组 中,在给定的时间点,只有一个进程 必须执行其临界区。如果任何其他进程 想要执行其关键部分,则它必须等到第一个 结束。

一般的信号可以允许多个进程进入临界区面积,但我不能看到如何在此代码完成。

这是不正确的,如果您允许多个进程到想要修改共享数据的关键部分,那么您可以更改关键部分的平均值。您将在流程结束时收到错误的数据。

如果进程只读取共享数据,一般信号量可用于允许多个进程访问关键数据,而不会修改共享数据。

我有很小的代码让你看看信号量如何工作以及多个进程如何允许访问共享数据。你可以把它当作多个读者和一个作家。

semaphore mutex = 1;     // Controls access to the reader count 
semaphore db = 1;     // Controls access to the database 
int reader_count;     // The number of reading processes accessing the data 

Reader() 
{ 
    while (TRUE) {      // loop forever 
    down(&mutex);       // gain access to reader_count 
    reader_count = reader_count + 1;  // increment the reader_count 
    if (reader_count == 1) 
     down(&db);       // if this is the first process to read the database, 
              // a down on db is executed to prevent access to the 
              // database by a writing process 
    up(&mutex);       // allow other processes to access reader_count 
    read_db();        // read the database 
    down(&mutex);       // gain access to reader_count 
    reader_count = reader_count - 1;  // decrement reader_count 
    if (reader_count == 0) 
     up(&db);       // if there are no more processes reading from the 
              // database, allow writing process to access the data 
    up(&mutex);       // allow other processes to access reader_countuse_data(); 
              // use the data read from the database (non-critical) 
} 

Writer() 
{ 
    while (TRUE) {      // loop forever 
    create_data();       // create data to enter into database (non-critical) 
    down(&db);        // gain access to the database 
    write_db();       // write information to the database 
    up(&db);        // release exclusive access to the database 
} 
相关问题