gen信号量使用二进制信号量实现:

因此,我很难理解为什么我们需要输入信号量,我可以看到它是如何正确地工作,没有它。多个进程如何进入关键部分?在第一个进程进入后,它会等待(互斥),这意味着没有其他人能够进入,而且还有其他进程等待信号(互斥)。
通用信号量可以允许多个进程进入关键区段区域,但我不知道在这段代码中是如何做到的。
发布于 2016-12-16 08:32:46
看到问题图像后,输入信号量的目的是只允许单个进程/线程等待锁定,如果不使用它,其他进程将进入等待队列。
为什么我们需要入口信号量
多进程如何进入关键部分?
通用信号量可以允许多个进程进入关键部分区域,但我不知道这是如何在这段代码中完成的.
如果允许多个进程对希望修改共享数据的关键部分进行处理,则更改关键部分的平均值,这是不对的。在处理结束时,您会得到错误的数据。
通用信号量可用于允许多个进程访问关键数据,如果进程只读取共享数据,则不要修改共享数据。
我有非常小的代码供您演示信号量是如何工作的,以及多个进程如何允许访问共享数据。你可以把它当作多个读者和一个作家。
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
}发布于 2018-10-29 14:03:51
多个进程如何进入关键部分?在第一个进程进入之后,它会等待(互斥),这意味着没有其他人可以进入…。通用信号量可以允许多个进程进入临界区段区域。
这里提到一个关键部分是有点遗憾的,因为https://en.wikipedia.org/wiki/Critical_section通常被理解为一个程序的部分,不能一次执行多个进程。您实际上的意思是,一个通用(计数)信号量可能允许多个进程共享(一个池)资源。您现在的实现确实能够做到这一点,因为:在第一个进程进入并等待(互斥)之后,它立即继续,因为mutex已经初始化为1。然后,如果递减的c不小于0,它会执行signal(mutex),因此可以进入另一个进程。
https://stackoverflow.com/questions/41178303
复制相似问题