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.
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.
Lock types and functions are declared in
Represents a lock.
void lock_init (struct lock *lock)
lockas a new lock. The lock is not initially owned by any thread.
void lock_acquire (struct lock *lock)
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. Returns true if successful, false if the lock is already owned. Calling this function in a tight loop is a bad idea because it wastes CPU time, so use
void lock_release (struct lock *lock)
lock, which the current thread must own.
bool lock_held_by_current_thread (const struct lock *lock)
Returns true if the running thread owns
lock, false otherwise. 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.