How to protect shared code/ data in a multithreaded environment?
When supporting a multi threaded environment, it is necessary to protect shared data or code from other threads or ISRs. OSAL provides synchronisation primitives in the form of mutexes and semaphores, and also APIs to disable the scheduler and interrupts. Here we provide a brief summary of each with some notes about when they should be used. The most important part of the decision is to understand what you are looking to protect, data and/or code, and what you are looking to protect it from - threads, ISRs or both.
Mutexes: A mutex should be used by threads to control access to a set of data so that the data can be accessed without other threads modifying it.
Semaphores: Semaphores are a signal, and are not intended to be used to protect data.All OSAL semaphores are counting semaphores. This means that each time a counting semaphore if posted an internal counter is incremented, and each time time the counting semaphore is pended-on the count is decremented. If a thread pends on a semaphore when the count is zero then the thread will either block or return a failure depending on the pend options.