java如何实现信号量_使用二进制信号量实现通用信号量
看到你的問題圖像后,輸入信號量的目的是只允許單個進程/線程等待鎖定,如果你不使用它,其他進程將進入等待隊列 .
why we need the entry semaphore
條目信號量未使用任何值初始化,如果它是全局聲明的,則它將初始化為0.因此,如果條目信號量為0,則wait(條目)將僅允許單個進程進入,因為wait()功能檢查條目值是否小于零,然后進程將進入等待隊列 .
How can multiple processes enter the critical section?
一次只有一個過程可以在關鍵部分 - 否則關鍵部分是什么?
Critical Section是訪問共享變量的代碼段,必須作為原子操作執(zhí)行 . 這意味著在一組協(xié)作過程中,在給定的時間點,只有一個過程必須執(zhí)行其關鍵部分 . 如果任何其他進程也想要執(zhí)行其關鍵部分,則必須等到第一個進程完成 .
A general semaphore can allow multiple processes to enter the critical section area but I cannot see how that is done in this code.
這是不對的,如果您允許多個進程到關鍵部分誰想要修改共享數(shù)據(jù),那么您可以更改關鍵部分的平均值 . 您將在流程結束時收到錯誤的數(shù)據(jù) .
如果進程只讀取共享數(shù)據(jù),則可以使用常規(guī)信號量允許多個進程訪問關鍵數(shù)據(jù),不要修改共享數(shù)據(jù) .
我有非常小的代碼供您展示信號量如何工作以及多個進程如何允許訪問共享數(shù)據(jù) . 你可以把它作為多個讀者和作家 .
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
}
總結
以上是生活随笔為你收集整理的java如何实现信号量_使用二进制信号量实现通用信号量的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux怎么把目录设置群组,linux
- 下一篇: php置顶文章,php实现文章置顶功能的