我目前有一个任务,我应该为有界缓冲区问题制作一个信号量。我认为我的第一个代码是好的,应该可行(如果我理解信号量正确,我不确定btw)
该分配的第二部分是使用java库来实现信号量。我做对了吗? 我为作业的每个部分提供了两个代码块。我只需要验证我的代码是否正确,可能还有一些关于使用java信号量库的输入:)
semaphore mutex = 1;
semaphore fillCount = 0;
semaphore emptyCount = BUFFER_SIZE;
procedure producer() {
while (true) {
item = produceItem();
down(emptyCount);
down(mutex);
putItemIntoBuffer(item);
up(mutex);
up(fillCount);
}
}
procedure consumer() {
while (true) {
down(fillCount);
down(mutex);
item = removeItemFromBuffer();
up(mutex);
up(emptyCount);
consumeItem(item);
}
}
使用Java-Semaphore:
Semaphore semaphore = new Semaphore(1);
public producer(){
semaphore.acquire();
putItemIntoBuffer(item);
semaphore.release();
}
public consumer(){
semaphore.acquire();
removeItemFromBuffer(item);
semaphore.release();
}
答案 0 :(得分:1)
在您的第一个代码示例中,您使用二进制信号量和计数信号量。您也应该在Java实现中使用它。 我认为,您应该使用0初始化信号量(用于产品计数)。 当你使用1时,你可以从缓冲区中取出一个项目,当它仍然是空的时候。
Semaphore mutex = new Semaphore(1);
Semaphore productCount = new Semaphre(0);
public producer(){
mutex.acquire(); //entering critical section
putItemIntoBuffer(item); //produce your item in the exclusive mode
productCount.release(); //increase your product count
mutex.release(); //leave critical section
}
public consumer(){
mutex.acquire(); //entering critical section
if(productCount.availablePermits() > 0) //test if you have already poduced some items
{
removeItemFromBuffer(item); //remove your item in the exclusive mode
productCount.acquire(); //decrease your item count
}
mutex.release(); //leave critical section
}
答案 1 :(得分:0)
使用锁和条件对象
class BoundedBuffer {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
final Object[] items = new Object[100];
int putptr, takeptr, count;
public void put(Object x) throws InterruptedException {
lock.lock();
try {
while (count == items.length)
notFull.await();
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
notEmpty.signal();
} finally {
lock.unlock();
}
}
public Object take() throws InterruptedException {
lock.lock();
try {
while (count == 0)
notEmpty.await();
Object x = items[takeptr];
if (++takeptr == items.length) takeptr = 0;
--count;
notFull.signal();
return x;
} finally {
lock.unlock();
}
}
}