written 6.0 years ago by | • modified 5.9 years ago |
The methods of task synchronization are:
Synchronization primitives
Semaphore: counting semaphore and binary semaphore
A semaphore is created with initial count, which is the number of allowed holders of the semaphore lock. (initial count=1: binary sem) . Sem wait will decrease the count; while sem_signal will increase it. A task can get the semaphore when the count > 0; otherwise, block on it.
Mutex: similar to a binary semaphore, but mutex has an owner.
A semaphore can be “waited for” and “signaled” by any task, while only the task that has taken a mutex is allowed to release it.
Spinlock: lock mechanism for multi-processor systems,
A task wanting to get spinlock has to get a lock shared by all processors.
Read/write locks: protect from concurrent write, while allow concurrent read
Many tasks can get a read lock; but only one task can get a write lock. Before a task gets the write lock, all read locks have to be released.
Barrier: to synchronize a lot of tasks, They should wait until all of them have reached a certain “barrier.”
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 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: Mutexes are binary semaphores that include a priority inheritance mechanism.
Mutexes are the better choice for implementing simple mutual exclusion (hence 'MUT'ual 'EX'clusion).
A mutex allows exclusive access to the resource. The long form is Mutually Exclusion Semaphores (semaphore value of 0 or 1 but lock count can be 0 or greater for recursive locking).
A mutex is intended to protect a critical region. Mutex is similar to a binary semaphore, but mutex has an owner.
The main difference is that a semaphore can be “waited for” and “signaled” by any task, while only the task that has taken a mutex is allowed to release it.
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
S1;
signal(Sem);
}
in process P2
{
wait(Sem);
S2;
}