生产者消费者的标准实现方式如下:
useQueue
互斥锁emptyCount
大小为N
的信号量fullCount
大小为N
的信号量
生产:
down(emptyCount)
down(useQueue)
putItemIntoQueue(item)
up(useQueue)
up(fullCount)
消费:
down(fullCount)
down(useQueue)
item ← getItemFromQueue()
up(useQueue)
up(emptyCount)
如果down
的值为非正数,则线程会等待。而up
则会增加计数。
引用自维基百科文章。
为什么我们不能有像这样的东西:
class NewSemaphore {
int capacity, permits;
/**
* Initialize the semaphore with a max capacity
* @param n the max capacity
*/
NewSemaphore(int n) {
capacity = n;
permits = 0;
}
/**
* We usually never check this. Check if it's within limits.
* If not, wait
*/
synchronized void up() {
if (permits >= capacity) {
wait();
} else {
permits++;
notify();
}
}
/**
* Standard down/acquire function
*/
synchronized void down() {
if (permits <= 0) {
wait();
} else {
permits--;
notify();
}
}
}
这段代码将会被这样调用: produce:
up(mySemaphore)
down(useQueue)
putItemIntoQueue(item)
up(useQueue)
消费:
down(mySemaphore)
down(useQueue)
item ← getItemFromQueue()
up(useQueue)
我们为什么需要两个不同的变量
emptyCount
和fullCount
呢?