. .
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) {
request->next = requests;
request_t *remove() {
requests = request;
request = requests;
requests = requests->next;
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