私は、モニターの 2 つの異なる実装に遭遇しました。while ループを使用して、スリープに入る前とスリープから復帰するたびに特定の条件が true かどうかをチェックするもの。もう 1 つは、if 条件が true かどうかを 1 回チェックし、そうでない場合はスリープ状態になりますが、起動時に再度チェックしません。前者は Mesa セマンティクスを使用し、後者は Hoare セマンティクスを使用していると思います。ウィケペディアが生産者消費者問題 ( http://en.wikipedia.org/wiki/Producer-consumer_problem#Using_monitors ) を実装する方法は、Mesa セマンティクスを使用していると思います。Hoare を使用してこれをどのように達成しますか?
こんな感じでしょうか。
monitor ProducerConsumer{
int itemCount;
int nextCount;
condition full;
condition empty;
condition nextSem;
init(n){
itemCount = n;
}
void add(item){
wait(mutex);
if(itemCount == BUFFER_SIZE){
cwait(full)
}
putItemIntoBuffer(item);
itemCount = itemCount + 1;
if(itemCount == 1){
csignal(empty);
}
//To give priority to threads already in the monitor over
//"normal" threads that want to enter the monitor for the
//first time.
if(nextCount>0){
signal(nextSem);
}else{
signal(mutex);
}
}
void consume(){
wait(mutex);
if(itemCount == 0){
cwait(empty);
}
item = removeItemFromBuffer();
itemCount = itemCount - 1;
if(itemcount == BUFFER_SIZE - 1 ){
csignal(full);
}
//To give priority to threads already in the monitor over
//"normal" threads that want to enter the monitor for the
//first time.
if(nextCount>0){
signal(nextSem);
}else{
signal(mutex);
}
}
cwait(sem x){
x.cnt = x.cnt + 1;
if(nextCount > 0)
signal(nextSem);
else
signal(mutex);
endif
wait(x);
x.cnt = x.cnt - 1;
}
csignal(sem x){
if(x.cnt > 1){
nextCount = nextCount + 1;
signal(x);
wait(nextSem);
nextCount = nextCount -1;
}
}
}