img
. .
mutex. To run condSignal(), it needs to obtain the synchronization for the condition variable,
which is still held by thread 1. Deadlock.[16]
[16]
By moving the condSignal() call in the P/C code outside the call to mutex.unlock(), this particular
version of the problem could be resolved, but slightly more subtle versions of it would still be there
for other situations. Consider having two consumers and one producer.
Code Example 6-22 shows how we'll write our producer/ consumer model using condition
variables. This code is perfectly correct and will work correctly on all platforms for any number of
producers, consumers, and size limits. Note that we now are forced to use explicit mutexes instead
of synchronized methods. The reason is that the data must be protected by the same lock in every
instance. If we tried to use synchronized methods, we'd be unable to have our two condition
variables both release that synchronization.
Example 6-22 Producer/Consumer Model Using POSIX-Style Synchronization
public class Consumer implements Runnable {
...
public void run()
{
Item item;
while (true) {
workpile.mutex.lock();
while (workpile.empty()) {
workpile.consumerCV.condWait(workpile.mutex);
}
item = workpile.remove();
workpile.producerCV.condSignal();
// Normally unlock
first
workpile.mutex.unlock();
}
server.process(item);
}
}
public class Producer implements Runnable {
...
public void run()
{
Item item;
while (true) {
item = server.get();
workpile.mutex.lock();
while (workpile.full()) {
workpile.producerCV.condWait(workpile.mutex);
}
workpile.add(item);
workpile.consumerCV.condSignal();
// Normally unlock
first
workpile.mutex.unlock();
}
}
}
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home