Sobes.tech
Junior — Middle

What types of locks are used in multithreaded programming to control access to resources?

sobes.tech AI

Answer from AI

In multithreaded programming, various types of locks are used to control access to shared resources:

  • Mutexes (Mutex) — provide exclusive access to a resource, allowing only one thread to own the lock at a time.
  • Recursive mutexes — allow the same thread to acquire the lock multiple times without causing a deadlock.
  • Semaphores — limit the number of threads that can access a resource simultaneously (for example, limiting to N threads).
  • ReadWriteLock — allow multiple threads to read a resource simultaneously, but writing blocks all others.
  • Spinlock — the thread actively waits for the lock to be released without sleeping, which is efficient for short lock durations.

In Java, classes from the java.util.concurrent.locks package are commonly used, such as ReentrantLock (a recursive mutex) and ReadWriteLock.

Example of using ReentrantLock:

ReentrantLock lock = new ReentrantLock();

lock.lock();
try {
    // critical section
} finally {
    lock.unlock();
}