Skip to main content Link Menu Expand (external link) Document Search Copy Copied

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.

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 threads/synch.h.

struct lock

Represents a lock.

void lock_init (struct lock *lock)

Initializes lock as a new lock. The lock is not initially owned by any thread.

void lock_acquire (struct lock *lock)

Acquires lock for the current thread, first waiting for any current owner to release it if necessary.

bool lock_try_acquire (struct lock *lock)

Tries to acquire lock for 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 lock_acquire instead.

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 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.