简体   繁体   中英

Why acquire a lock in a release operation

In the context of creating a monitor to manage access to a single resource, my professor gave us this code:

private final Lock monitor;       
private final Condition nonBusy; 
private boolean busy;             

// acquire resource
public void acquire() throws InterruptedException {
    monitor.lock();     
    try {   
        while(busy)
            nonBusy.await();            
        busy = true;    
    } finally {
        monitor.unlock();   
    }
}

// release the previously acquired resource 
public void release() {
    monitor.lock();
    try {
        busy = false;       
        nonBusy.signal();   
    } finally {
        monitor.unlock();
    }
}

Why the unlock in the end of the acquire operation and the lock in the start of release operation ? If I just acquired access to the resource, why release the lock I have for it?

Basically, you are using a Lock , a boolean flag, and a condition variable to implement the equivalent of a Lock . You are correct in thinking that it is entirely redundant. I think your professor is just giving you an exercise to show the correct way to wait for a condition, and the correct way to signal one. Could have been a little more creative with coming up with a reason to wait, and a reason to signal, but whatever. What's important is the pattern that is embodied by those acquire() and release() functions.

Note that it's not an example of how locks really are implemented at the operating system level because it's missing the notion of a wait set . That is, the set of threads that are waiting to acquire any given lock, the set of threads that are waiting to be awakened by a condition.signal() call, the set of threads that are waiting for a CPU to run on, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM