The methods of task synchronization are: Semaphore Message queue. Mutual exclusion. Dead lock. Mailboxes. Message Queues.
Semaphores: It is a system of sending message by using flags. Multiple concurrent threads of execution with an application must be able to synchronize their execution & co-ordinate mutually exclusive access to shared resources. To fulfill this requirement RTOS kernel provides a semaphore object that one or more threads of execution can acquire or release for the purpose of synchronization or mutual exclusion. Semaphore is like a key that allows a test to carry out some operation or to access a resource. When task acquires the semaphore, it receives an access to the resource. The number of times the semaphore can be acquired by the task is determined by the resource count of a semaphore. A resource count is decremented by one, when a task acquires the semaphore and its resource count is incremented by one when a task releases the semaphore. A kernel supports many different types of semaphores :
Binary: Binary semaphores are used for both mutual exclusion and synchronization purposes. A binary semaphore is used to control sharing a single resource between tasks..
Counting: it is a semaphore that increments when an IPC is given by a task. It decrements when a waiting task unblocks and starts running.
Mutex or Mutually Exclusion semaphore: In this a mutex key is used to lock the shared resource, if it is acquired by the task, so that any other task cannot acquire until it is released.
Example of using semaphores for Synchronization: Assume two concurrent process P1 and P2 having statements S1 and S2. We want in any case S1 should execute first. this can be achieved easily by initialize Sem=0;
In process P1
// Execute whatever you want to do
// before executing P2
in process P2