. .
interesting to notice that the number of items on the list is contained in the semaphore, but the
program never actually gets to look at that number. Should the producer place twenty items on the
list all at once, the consumer function will be able to call sem_wait() twenty times without
blocking. The twenty-first time, the semaphore will be zero, and the consumer will have to wait.
Because the critical sections are so small, the chance of any thread ever blocking on the mutex in
get_request() is very small.
In Code Example 6-12, the main things to notice are that get_request() must allocate the
memory for the request structure that will be appended to the list, while process_request() is
responsible for freeing it. This code may safely be run by any number of threads running the
producer and any number running the consumer. In no case will a consumer ever attempt to
remove a request from an empty list. The semaphore actually encodes the minimum length of the
list. During the brief moments between the time a producer places a request onto the list and the
time the semaphore is incremented, the semaphore value is one less than the actual length of the
list. For now, this is fine.
Example 6-12 Classic Producer/Consumer Example (one_queue_problem.c)
producer() {
request_t *request;
while(TRUE) {
request = get_request();
consumer() {
request_t *request;
while(TRUE) {
request = remove();
The same problem done in Java (Code Example 6-13) is quite similar again. Unlike C, there will
be no issues surrounding allocating and freeing memory (ain't garbage collection great?).
Example 6-13 Classic Producer/Consumer Example (OneQueueProblem)
public class Consumer implements Runnable {
Workpile workpile;
Server server;
public void run() {
Item item;
while (true) {
item = workpile.remove();
public class Producer implements Runnable {
Workpile workpile;
Server server;
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks