java如何实现信号量_使用二进制信号量实现通用信号量

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

why we need the entry semaphore

条目信号量未使用任何值初始化,如果它是全局声明的,则它将初始化为0.因此,如果条目信号量为0,则wait(条目)将仅允许单个进程进入,因为wait()功能检查条目值是否小于零,然后进程将进入等待队列 .

How can multiple processes enter the critical section?

一次只有一个过程可以在关键部分 - 否则关键部分是什么?

Critical Section是访问共享变量的代码段,必须作为原子操作执行 . 这意味着在一组协作过程中,在给定的时间点,只有一个过程必须执行其关键部分 . 如果任何其他进程也想要执行其关键部分,则必须等到第一个进程完成 .

A general semaphore can allow multiple processes to enter the critical section area but I cannot see how that is done in this code.

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

如果进程只读取共享数据,则可以使用常规信号量允许多个进程访问关键数据,不要修改共享数据 .

我有非常小的代码供您展示信号量如何工作以及多个进程如何允许访问共享数据 . 你可以把它作为多个读者和作家 .

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

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值