Locks
A lock is like a semaphore with an initial value of 1. A lock’s equivalent of "up" is called "release", and the "down" operation is called "acquire".
Compared to a semaphore, a lock has one added restriction: only the thread that acquires a lock, called the lock’s “owner”, is allowed to release it. If this restriction is a problem, it’s a good sign that a semaphore should be used, instead of a lock.
You may also want to read through the Study Guide related to Locks for more information.
Locks in PintOS are not “recursive”, that is, it is an error for the thread currently holding a lock to try to acquire that lock again.
Lock types and functions are declared in threads/synch.h.
struct lock
Represents a lock.
void lock_init (struct lock *lock)
Initializes
lockas a new lock. The lock is not initially owned by any thread.
void lock_acquire (struct lock *lock)
Acquires
lockfor the current thread, first waiting for any current owner to release it if necessary.
bool lock_try_acquire (struct lock *lock)
Tries to acquire
lockfor use by the current thread, without waiting. Returnstrueif successful,falseif the lock is already owned. Calling this function in a tight loop is a bad idea because it wastes CPU time, so uselock_acquireinstead.
void lock_release (struct lock *lock)
Releases
lock, which the current thread must own.
bool lock_held_by_current_thread (const struct lock *lock)
Returns
trueif the running thread ownslock,falseotherwise. There is no function to test whether an arbitrary thread owns a lock, because the answer could change before the caller could act on it.