Câu hỏi phỏng vấn Concurrency
Câu hỏi

Is there any difference between a Binary Semaphore and Mutex?

Câu trả lời

The difference between a binary semaphore and a mutex lies in their mechanisms, usage, and certain operational constraints. Here is a detailed comparison:

Mechanism

  • Mutex: A mutex (short for mutual exclusion) is a locking mechanism used to ensure that only one thread can access a resource at a time. It is specifically designed for mutual exclusion and is typically used to protect critical sections of code.
  • Binary Semaphore: A binary semaphore is a signaling mechanism that can have only two values, 0 and 1. It is used to signal the availability of a resource and can be used for both mutual exclusion and synchronization between threads or processes.

Ownership

  • Mutex: A mutex has ownership, meaning that the thread that locks the mutex must be the one to unlock it. This ownership constraint helps prevent issues such as accidental release and ensures that only the owning thread can release the lock[1][3][6].
  • Binary Semaphore: A binary semaphore does not have ownership. Any thread or process can signal (release) the semaphore, which can lead to potential issues if not managed carefully[1][3][6].

Usage

  • Mutex: Typically used for protecting critical sections where only one thread should execute at a time. It is ideal for scenarios where the resource being protected should not be accessed by more than one thread simultaneously[1][3][6].
  • Binary Semaphore: Used for signaling and coordination between threads or processes. It can be used to implement mutual exclusion but is also suitable for other synchronization tasks, such as signaling between producer and consumer threads[1][3][6].

Performance

  • Mutex: Generally faster and more lightweight compared to semaphores. Mutexes are optimized for the specific use case of mutual exclusion[1][3][6].
  • Binary Semaphore: Slightly slower than mutexes because they are more general-purpose and can be used for a wider range of synchronization tasks[1][3][6].

Priority Inheritance

  • Mutex: Often supports priority inheritance to prevent priority inversion, where a lower-priority thread holds a mutex needed by a higher-priority thread[5][8].
  • Binary Semaphore: Typically does not support priority inheritance, which can lead to priority inversion issues if not managed properly[5][8].

Scope

  • Mutex: Usually limited to synchronization within a single process. It is used for...
middle

middle

Gợi ý câu hỏi phỏng vấn

senior

Provide some real-live examples of Livelock

middle

What is a Race Condition?

senior

What is Green Thread?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào