Semaphore
Semaphore
1
Overview
A semaphore is a kernel primitive object.
Semaphore operations:
(1) Can change a task’s state.
(2) Are fast.
Three semaphores types available:
(1) Binary semaphores allow a task to pend until a given event
occur(e.g. an Interrupt).
(2) Mutual exclusion semaphores allow a task to acquire an
exclusive lock to a shared resource(e.g. a file or a device).
(3) Counting semaphores are used with multiple resources of
same type
2
Binary semaphores
&
Synchronization
3
The synchronization problem
Task may need to wait for an event to occur.
Busy waiting (ie.polling) is inefficient.
Pending until the event occurs is better.
myGetData()
{
requestData()
TASK WaitForData()
getData()
}
4
The Synchronization solutions
Create a binary semaphore for that event.
Binary semaphores exist in one of the two states:
- Full (event has occurred).
- Empty (event has not occurred).
Task waiting for the event calls semTake() &blocks
until semaphore is given.
Task or Interrupt service routine detecting the event
calls semGive() which unblocks the waiting task.
5
Binary Semaphores
SEM_ID semBCreate(options,initial State)
Option :Specify queue type(SEM_Q_PRIORITY or
SEM_Q_FIFO) for tasks pended on this semaphore.
Initial State :Initialize semaphore to be available
(SEM_FULL) or unavailable(SEM_EMPTY).
Semaphores used for synchronization are typically
initialized to SEM_EMPTY(event has not
occurred).
Returns a SEM_ID,or NULL on ERROR.
6
Taking a semaphore
STATUS semTake(semid,timeout)
semid : The SEM_ID returned from semBCreate().
timeout : Maximum time to wait for semaphore.Value
can be clock ticks,WAIT_FOREVER or NO_WAIT.
Can pend the task until either:
Semaphore is given,or
Timeout expires.
Semaphore left unavailable.
7
Taking a binary semaphore contd……..
Semaphore No timeout
Task pends until sem is given Task pends until sem is given
Available? Or timeout Or timeout
Semaphore
Yes given
8
Giving a semaphore
STATUS semGive(semid)
Unblocks a task waiting for semid.
If no task is waiting,make semid available.
Returns OK,or ERROR if semid is invalid.
9
Giving a binary semaphore
Tasks No
Pended? Semaphore made available.
yes
10
Synchronizing Multiple tasks
STATUS semFlush(semid)
Unblocks all tasks waiting for semaphore.
11
Common Routines
Additional semaphore routines:
semDelete() Destroy the semaphore.semTake() calls
for all tasks pended on the semaphore
return ERROR.
12
Semaphore browser
To insert the properties of a specific semaphore
insert the semaphore ID in the Browser’s show
box &click on show.
13
Summary
Binary semaphores allow task to pend until some
event occurs.
Create a binary semaphore for the given event.
Tasks waiting for the event blocks on a
semTake().
Task or ISR detecting the event calls
semGive() or semFlush().
Caveat : If the event repeats too quickly ,information
may be lost.
14
THANK YOU
15