img
. .
the sleeper, would remove Request2 from the list. Presumably all the threads will be executing
the same code, so it won't make any difference which thread actually gets to process the request.
Figure 6-3. Protecting a Shared List with a Mutex
Example 6-4 Protecting a Shared List with a Mutex (POSIX)
Thread 1
Thread 2
add(request_t *request) {
pthread_mutex_lock(&lock);
request->next = requests;
request_t *remove() {
requests = request;
pthread_mutex_lock(&lock);
pthread_mutex_unlock(&lock);
...sleeping...
}
request = requests;
requests = requests->next;
pthread_mutex_unlock(&lock)
return(request);
}
The same lock must be used uniformly to protect data. Using one lock to protect the list in add()
and a different lock in remove() would be a disaster, of course. Don't do that.
Now let's look at how Java implements mutual exclusion. The computational logic for Java is
identical; the coding technique is different. In Java, a block of code marked synchronized will
be protected by a mutex.
In Java every object has a mutex associated with it implicitly (Figure 6-4). There is no direct
access to this mutex; rather, it is locked and unlocked through the use of synchronized statements.
A synchronized statement has the form shown in Code Example 6-5.
Figure 6-4. All Objects Have Their Own Mutex and Wait Set
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home