

A

Discuss the differences between a mutex and a binary semaphore in the context of real-time operating systems (RTOS). What are the key characteristics of each, and in what scenarios would you prefer one over the other?
A mutex (mutual exclusion) is a locking mechanism that allows only one thread to access a resource at a time. It is used to protect shared data from being simultaneously accessed by multiple threads, ensuring data integrity.
mutex.acquire() # Lock the mutex
# Critical section
mutex.release() # Unlock the mutex
A binary semaphore is a signaling mechanism that can be used to manage access to shared resources. Unlike a mutex, it does not enforce ownership, allowing different threads to release the semaphore.
binary_semaphore.wait() # Wait (decrement)
# Critical section
binary_semaphore.signal() # Signal (increment)
Mutexes enforce ownership, meaning only the thread that locked the mutex can unlock it, preventing accidental release by other threads. In contrast, binary semaphores do not have this restriction.
Mutexes are ideal for protecting shared resources and ensuring data consistency, while binary semaphores are suitable for signaling between threads or managing resource availability.