Saturday, July 13, 2013

Event flag Vs Semaphore: Waiting for event/resource

① Waiting for event flag
In case of event flag, a few more arguments like the flag pattern for waiting, mode for waiting has to be passed. In binary semaphore, it is more simple, only the semaphore id.
 
Event flag can synchronize multiple tasks on a single event. Like single shoot triggers many marathon runners. With binary semaphore, it is not possible. But, with counting semaphore (multiple resource count), it is possible.
 
But implementation, it is almost same as semaphore except that each task context need to save few more arguments passed in wai_flg() function. (The arguments which vary depend on calling task needs to be preserved in task context)

② ITRON implementation to wait for event
ER wai_flg(ID flgid, UINT waiptn, UINT wfmode, UINT *p_flgptn)
{
        Sanity check on arguments
        If (only single task is allowed to wait (TA_WSGL, TA_WMUL flags)
                        and already a task is waiting)
                return E_ILUSE;
        If (the event pattern does not match the waiting pattern) {
                If (this function is called from interrupt context) or
                If (called from task independent state ex: timer handlers) or
                If (called from dispatch disabled state)
                        Return E_CTX;
                If (polling mode)
                        Exit critical section and return E_TMOUT;
                If (Timeout value is specified) {
                        Add task into timer queue;
                        Set TCB flags that 'Waiting for flag, Check for Timeout'
                } else (Wait forever) {
                        Set TCB flags that 'Waiting forever for flag'
                }
                Set event flag ID in TCB
                Also save parameters like waiting mode, waiting pattern,
                        pointer to return bit pattern and even flag attributes
                Select Queue according to queueing order
                If (Tasks should be granted in FIFO order)
                        Select Flag->Queue[0] as Queue
                Else (Should be granted in Priority order)
                        Select Flag->Queue[Current Tasks Priority]
                Change the task from ReadyQueue to the Flag Queue
                Schedule the tasks, since this task is going to sleep
                (Once the task is released, execution will return here)
                Return the value set by scheduler(Scheduler directly set return value before return here)
        }
        Store the pattern into the pointer for returning bit pattern
        If the bit pattern has to be cleared (TA_CLR flag) {
                Clear the flag pattern
        }
        Exit critical secion
        Return E_OK;
}

For other posts, visit posts under RTOS label.

No comments: