【 uC/OS II 】uC/OS II 源代码阅读(os_sem.c)信号量

前言

不说了,这个太简单了,没啥可说的,核心结构体还是这个:

#if (OS_EVENT_EN) && (OS_MAX_EVENTS > 0u)
typedef struct os_event {
    INT8U    OSEventType;                   /* Type of event control block (see OS_EVENT_TYPE_xxxx)    */
    void    *OSEventPtr;                    /* Pointer to message or queue structure                   */
    INT16U   OSEventCnt;                    /* Semaphore Count (not used if other EVENT type)          */
    OS_PRIO  OSEventGrp;                    /* Group corresponding to tasks waiting for event to occur */
    OS_PRIO  OSEventTbl[OS_EVENT_TBL_SIZE]; /* List of tasks waiting for event to occur                */

#if OS_EVENT_NAME_EN > 0u
    INT8U   *OSEventName;
#endif
} OS_EVENT;
#endif

核心就是变量:(OSEventCnt)信号量的个数、(OSEventGrp)等待组、(OSEventTbl)等待表,结构体里面的OSEventPtr没啥大作用,它在没用的时候,是用来连接空闲的OS_EVENT链表的。

/*普通信号量(已看)
*********************************************************************************************************
*                                                uC/OS-II
*                                          The Real-Time Kernel
*                                          SEMAPHORE MANAGEMENT
*
*                           (c) Copyright 1992-2017; Micrium, Inc.; Weston; FL
*                                           All Rights Reserved
*
* File    : OS_SEM.C
* By      : Jean J. Labrosse
* Version : V2.92.13
*
* LICENSING TERMS:
* ---------------
*   uC/OS-II is provided in source form for FREE evaluation, for educational use or for peaceful research.
* If you plan on using  uC/OS-II  in a commercial product you need to contact Micrium to properly license
* its use in your product. We provide ALL the source code for your convenience and to help you experience
* uC/OS-II.   The fact that the  source is provided does  NOT  mean that you can use it without  paying a
* licensing fee.
*
* Knowledge of the source code may NOT be used to develop a similar product.
*
* Please help us continue to provide the embedded community with the finest software available.
* Your honesty is greatly appreciated.
*
* You can find our product's user manual, API reference, release notes and
* more information at https://doc.micrium.com.
* You can contact us at www.micrium.com.
*********************************************************************************************************
*/

#define  MICRIUM_SOURCE

#ifndef  OS_MASTER_FILE
#include <ucos_ii.h>
#endif

#if OS_SEM_EN > 0u
/*
*********************************************************************************************************
*                                          ACCEPT SEMAPHORE(无等待请求信号量)
*
* Description: This function checks the semaphore to see if a resource is available or, if an event
*              occurred.  Unlike OSSemPend(), OSSemAccept() does not suspend the calling task if the
*              resource is not available or the event did not occur.
*当一个事件发生的时候,这个函数被用来检查信号量,来查看资源是否可用,不像OSSemPend(),OSSemAccept()当请求的资源不可用或者事件并未发生的时候并不挂起请求资源的任务
* Arguments  : pevent     is a pointer to the event control block
*指向ECB的指针
* Returns    : >  0       if the resource is available or the event did not occur the semaphore is
*                         decremented to obtain the resource.
如果资源可用或事件未发生,则减少信号量以获取资源。
*              == 0       if the resource is not available or the event did not occur or,
*                         if 'pevent' is a NULL pointer or,
*                         if you didn't pass a pointer to a semaphore
如果信号量不可用,或者事件尚未发生,如果pevent是一个空指针,如果你并没有给信号量传递一个指针
*********************************************************************************************************
*/

//是否允许无等待请求信号量
#if OS_SEM_ACCEPT_EN > 0u
INT16U  OSSemAccept (OS_EVENT *pevent)
{
    INT16U     cnt;
#if OS_CRITICAL_METHOD == 3u                          /* Allocate storage for CPU status register      */
    OS_CPU_SR  cpu_sr = 0u;
#endif


//参数检查
#if OS_ARG_CHK_EN > 0u
    if (pevent == (OS_EVENT *)0) {                    /* Validate 'pevent'                             */
        return (0u);
    }
#endif
//验证ECB的类型是否为信号量类型
    if (pevent->OSEventType != OS_EVENT_TYPE_SEM) {   /* Validate event block type                     */
        return (0u);
    }
    OS_ENTER_CRITICAL();//进入临界区,关中断
    //获取事件控制块当前信号量的值
    cnt = pevent->OSEventCnt;
    if (cnt > 0u) {                                   /* See if resource is available                  */
        //如果信号量的值可用,则减一
        pevent->OSEventCnt--;                         /* Yes, decrement semaphore and notify caller    */
    }
    OS_EXIT_CRITICAL();
    //返回信号量未减少之前的信号量
    return (cnt);                                     /* Return semaphore count                        */
}
#endif


/*
*********************************************************************************************************
*                                         CREATE A SEMAPHORE(创建一个信号量)
*
* Description: This function creates a semaphore.
*这个函数用来创建一个信号量
* Arguments  : cnt           is the initial value for the semaphore.  If the value is 0, no resource is
*                            available (or no event has occurred).  You initialize the semaphore to a
*                            non-zero value to specify how many resources are available (e.g. if you have
*                            10 resources, you would initialize the semaphore to 10).
*cnt 是为信号量赋的初始值,如果这个值是0,表示无资源可用(或者事件尚未发生)。你用非零值初始化这个信号量来表示资源有效的数量是多少。(例如,如果你有10个资源,那么你需要初始化这个信号量为10)
* Returns    : != (void *)0  is a pointer to the event control block (OS_EVENT) associated with the
*                            created semaphore
如果不是(void*)0 :那么返回的是指向与信号量相关的ECB的指针
*              == (void *)0  if no event control blocks were available
如果没有多余的ECB资源,那么返回(void*)0
*********************************************************************************************************
*/

OS_EVENT  *OSSemCreate (INT16U cnt)
{
    OS_EVENT  *pevent;
#if OS_CRITICAL_METHOD == 3u                               /* Allocate storage for CPU status register */
    OS_CPU_SR  cpu_sr = 0u;
#endif


#ifdef OS_SAFETY_CRITICAL_IEC61508
    if (OSSafetyCriticalStartFlag == OS_TRUE) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return ((OS_EVENT *)0);
    }
#endif

//不能再中断服务程序中创建信号量
    if (OSIntNesting > 0u) {                               /* See if called from ISR ...               */
        return ((OS_EVENT *)0);                            /* ... can't CREATE from an ISR             */
    }
    //进入临界区,关中断
    OS_ENTER_CRITICAL();
    //从ECB空闲链表中获取一个ECB
    pevent = OSEventFreeList;                              /* Get next free event control block        */
    //如果OSEventFreeList不为空,那么就将其指向下一个ECB
    if (OSEventFreeList != (OS_EVENT *)0) {                /* See if pool of free ECB pool was empty   */
        OSEventFreeList = (OS_EVENT *)OSEventFreeList->OSEventPtr;
    }
    OS_EXIT_CRITICAL();//退出临界区,开中断
    //再次核实,是否获得了一个新的ECB,随后对新的ECB进行一些设置
    if (pevent != (OS_EVENT *)0) {                         /* Get an event control block               */
        pevent->OSEventType    = OS_EVENT_TYPE_SEM;
        pevent->OSEventCnt     = cnt;                      /* Set semaphore value                      */
        pevent->OSEventPtr     = (void *)0;                /* Unlink from ECB free list                */
//是否允许使用ECB名字
#if OS_EVENT_NAME_EN > 0u
        pevent->OSEventName    = (INT8U *)(void *)"?";
#endif
//初始化时间等待表/组
        OS_EventWaitListInit(pevent);                      /* Initialize to 'nobody waiting' on sem.   */
        
        OS_TRACE_SEM_CREATE(pevent, pevent->OSEventName);
    }
    return (pevent);
}


/*
*********************************************************************************************************
*                                         DELETE A SEMAPHORE(删除一个信号量)
*
* Description: This function deletes a semaphore and readies all tasks pending on the semaphore.
*这个函数删除一个信号量,并且释放所有在等待此信号量的任务
* Arguments  : pevent        is a pointer to the event control block associated with the desired
*                            semaphore.
*与期待的信号量相关的ECB的指针
*              opt           determines delete options as follows:决定了信号量删除的方式
*                            opt == OS_DEL_NO_PEND   Delete semaphore ONLY if no task pending
                                                    仅当没有任务在等待的时候才删除信号量
*                            opt == OS_DEL_ALWAYS    Deletes the semaphore even if tasks are waiting.
*                                                    In this case, all the tasks pending will be readied.
*                                                   无论是否有任务在等待信号量,都会删除信号量,所有等待信号量的任务都会被变为就绪态
*              perr          is a pointer to an error code that can contain one of the following values:
*                            OS_ERR_NONE                  The call was successful and the semaphore was
*                                                         deleted
*                            OS_ERR_DEL_ISR               If you attempted to delete the semaphore from an
*                                                         ISR
*                            OS_ERR_ILLEGAL_DEL_RUN_TIME  If you tried to delete the semaphore after
*                                                         safety critical operation started.
*                            OS_ERR_INVALID_OPT           An invalid option was specified
*                            OS_ERR_TASK_WAITING          One or more tasks were waiting on the semaphore
*                            OS_ERR_EVENT_TYPE            If you didn't pass a pointer to a semaphore
*                            OS_ERR_PEVENT_NULL           If 'pevent' is a NULL pointer.
*
* Returns    : pevent        upon error
*              (OS_EVENT *)0 if the semaphore was successfully deleted.
*
* Note(s)    : 1) This function must be used with care.  Tasks that would normally expect the presence of
*                 the semaphore MUST check the return code of OSSemPend().
*              2) OSSemAccept() callers will not know that the intended semaphore has been deleted unless
*                 they check 'pevent' to see that it's a NULL pointer.
*              3) This call can potentially disable interrupts for a long time.  The interrupt disable
*                 time is directly proportional to the number of tasks waiting on the semaphore.
*              4) Because ALL tasks pending on the semaphore will be readied, you MUST be careful in
*                 applications where the semaphore is used for mutual exclusion because the resource(s)
*                 will no longer be guarded by the semaphore.
*              5) All tasks that were waiting for the semaphore will be readied and returned an
*                 OS_ERR_PEND_ABORT if OSSemDel() was called with OS_DEL_ALWAYS
注意:1)必须谨慎使用此功能。 通常期望信号量存在的任务必须检查OSSemPend()的返回码。
     2)OSSemAccept()调用者将不知道预期的信号已被删除,除非他们检查“ pevent”以查看它是否为NULL指针。
     3)此调用可能会长时间禁用中断。 中断禁用时间与等待信号量的任务数量成正比。
     4)因为所有准备在信号量上的任务都将准备就绪,所以在将信号量用于互斥的应用程序中必须小心,因为资源将不再受到信号量的保护。
     5)如果使用OS_DEL_ALWAYS调用了OSSemDel(),将准备所有等待信号量的任务并返回OS_ERR_PEND_ABORT
*********************************************************************************************************
*/

//是否允许信号量的删除
#if OS_SEM_DEL_EN > 0u
OS_EVENT  *OSSemDel (OS_EVENT  *pevent,
                     INT8U      opt,
                     INT8U     *perr)
{
    BOOLEAN    tasks_waiting;//标记是否有任务在等待此信号量
    OS_EVENT  *pevent_return;
#if OS_CRITICAL_METHOD == 3u                               /* Allocate storage for CPU status register */
    OS_CPU_SR  cpu_sr = 0u;
#endif


#ifdef OS_SAFETY_CRITICAL
    if (perr == (INT8U *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return ((OS_EVENT *)0);
    }
#endif

#ifdef OS_SAFETY_CRITICAL_IEC61508
    if (OSSafetyCriticalStartFlag == OS_TRUE) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        *perr = OS_ERR_ILLEGAL_DEL_RUN_TIME;
        return ((OS_EVENT *)0);
    }
#endif

//参数检查
#if OS_ARG_CHK_EN > 0u
    if (pevent == (OS_EVENT *)0) {                         /* Validate 'pevent'                        */
        *perr = OS_ERR_PEVENT_NULL;
        return (pevent);
    }
#endif

    OS_TRACE_SEM_DEL_ENTER(pevent, opt);
//验证是否为信号量类型
    if (pevent->OSEventType != OS_EVENT_TYPE_SEM) {        /* Validate event block type                */
        *perr = OS_ERR_EVENT_TYPE;
        OS_TRACE_SEM_DEL_EXIT(*perr);
        return (pevent);
    }
    //ISR中不能删除信号量
    if (OSIntNesting > 0u) {                               /* See if called from ISR ...               */
        *perr = OS_ERR_DEL_ISR;                            /* ... can't DELETE from an ISR             */
        OS_TRACE_SEM_DEL_EXIT(*perr);
        return (pevent);
    }
    OS_ENTER_CRITICAL();//进入临界区,关中断
    //检查是否有任务在等待
    if (pevent->OSEventGrp != 0u) {                        /* See if any tasks waiting on semaphore    */
        tasks_waiting = OS_TRUE;                           /* Yes                                      */
    } else {
        tasks_waiting = OS_FALSE;                          /* No                                       */
    }
    //根据传入的不同参数,来决定处理方式
    switch (opt) {
        case OS_DEL_NO_PEND:                               /* Delete semaphore only if no task waiting */
             if (tasks_waiting == OS_FALSE) {
#if OS_EVENT_NAME_EN > 0u
                 pevent->OSEventName    = (INT8U *)(void *)"?";
#endif
                 pevent->OSEventType    = OS_EVENT_TYPE_UNUSED;
                 pevent->OSEventPtr     = OSEventFreeList; /* Return Event Control Block to free list  */
                 pevent->OSEventCnt     = 0u;
                 OSEventFreeList        = pevent;          /* Get next free event control block        */
                 OS_EXIT_CRITICAL();
                 *perr                  = OS_ERR_NONE;
                 pevent_return          = (OS_EVENT *)0;   /* Semaphore has been deleted               */
             } else {
                 OS_EXIT_CRITICAL();
                 *perr                  = OS_ERR_TASK_WAITING;
                 pevent_return          = pevent;
             }
             break;

        case OS_DEL_ALWAYS:                                /* Always delete the semaphore              */
             while (pevent->OSEventGrp != 0u) {            /* Ready ALL tasks waiting for semaphore    */
                 (void)OS_EventTaskRdy(pevent, (void *)0, OS_STAT_SEM, OS_STAT_PEND_ABORT);
             }
#if OS_EVENT_NAME_EN > 0u
             pevent->OSEventName    = (INT8U *)(void *)"?";
#endif
            //重设一下ECB中的参数,并将其插入到空闲链表中
             pevent->OSEventType    = OS_EVENT_TYPE_UNUSED;
             pevent->OSEventPtr     = OSEventFreeList;     /* Return Event Control Block to free list  */
             pevent->OSEventCnt     = 0u;
             OSEventFreeList        = pevent;              /* Get next free event control block        */
             OS_EXIT_CRITICAL();
             if (tasks_waiting == OS_TRUE) {               /* Reschedule only if task(s) were waiting  */
                 OS_Sched();                               /* Find highest priority task ready to run  */
             }
             *perr                  = OS_ERR_NONE;
             pevent_return          = (OS_EVENT *)0;       /* Semaphore has been deleted               */
             break;

        default:
             OS_EXIT_CRITICAL();
             *perr                  = OS_ERR_INVALID_OPT;
             pevent_return          = pevent;
             break;
    }

    OS_TRACE_SEM_DEL_EXIT(*perr);

    return (pevent_return);
}
#endif


/*
*********************************************************************************************************
*                                          PEND ON SEMAPHORE(等待一个信号量)
*
* Description: This function waits for a semaphore.
*这个函数的功能是等待一个信号量
* Arguments  : pevent        is a pointer to the event control block associated with the desired
*                            semaphore.
*与指定的信号量所相关联的ECB的指针
*              timeout       is an optional timeout period (in clock ticks).  If non-zero, your task will
*                            wait for the resource up to the amount of time specified by this argument.
*                            If you specify 0, however, your task will wait forever at the specified
*                            semaphore or, until the resource becomes available (or the event occurs).
*是可选的超时时间(以时钟滴答为单位)。 如果不为零,则您的任务将等待资源直至此参数指定的时间。 但是,如果指定0,则任务将在指定的信号量下永远等待,或者直到资源可用(或事件发生)为止。
*              perr          is a pointer to where an error message will be deposited(存入).  Possible error
*                            messages are:
*
*                            OS_ERR_NONE         The call was successful and your task owns the resource
*                                                or, the event you are waiting for occurred.
*                            OS_ERR_TIMEOUT      The semaphore was not received within the specified
*                                                'timeout'.
*                            OS_ERR_PEND_ABORT   The wait on the semaphore was aborted(中止).
*                            OS_ERR_EVENT_TYPE   If you didn't pass a pointer to a semaphore.
*                            OS_ERR_PEND_ISR     If you called this function from an ISR and the result
*                                                would lead to a suspension.
*                            OS_ERR_PEVENT_NULL  If 'pevent' is a NULL pointer.
*                            OS_ERR_PEND_LOCKED  If you called this function when the scheduler is locked
*
* Returns    : none
*********************************************************************************************************
*/

void  OSSemPend (OS_EVENT  *pevent,
                 INT32U     timeout,
                 INT8U     *perr)
{
#if OS_CRITICAL_METHOD == 3u                          /* Allocate storage for CPU status register      */
    OS_CPU_SR  cpu_sr = 0u;
#endif


#ifdef OS_SAFETY_CRITICAL
    if (perr == (INT8U *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return;
    }
#endif

//参数检查
#if OS_ARG_CHK_EN > 0u
    if (pevent == (OS_EVENT *)0) {                    /* Validate 'pevent'                             */
        *perr = OS_ERR_PEVENT_NULL;
        return;
    }
#endif

    OS_TRACE_SEM_PEND_ENTER(pevent, timeout);
//检查ECB的类型
    if (pevent->OSEventType != OS_EVENT_TYPE_SEM) {   /* Validate event block type                     */
        *perr = OS_ERR_EVENT_TYPE;
        OS_TRACE_SEM_PEND_EXIT(*perr);
        return;
    }
    //ISR中不允许等待一个信号量
    if (OSIntNesting > 0u) {                          /* See if called from ISR ...                    */
        *perr = OS_ERR_PEND_ISR;                      /* ... can't PEND from an ISR                    */
        OS_TRACE_SEM_PEND_EXIT(*perr);
        return;
    }
    //当调度器上锁的时候,不允许等待一个信号量
    if (OSLockNesting > 0u) {                         /* See if called with scheduler locked ...       */
        *perr = OS_ERR_PEND_LOCKED;                   /* ... can't PEND when locked                    */
        OS_TRACE_SEM_PEND_EXIT(*perr);
        return;
    }
    OS_ENTER_CRITICAL();//进入临界区,关中断
    if (pevent->OSEventCnt > 0u) {                    /* If sem. is positive, resource available ...   */
        pevent->OSEventCnt--;                         /* ... decrement semaphore only if positive.     */
        OS_EXIT_CRITICAL();
        *perr = OS_ERR_NONE;
        OS_TRACE_SEM_PEND_EXIT(*perr);
        //请求成功,返回,开中断
        return;
    }

    //否则按照约定的等待事件进行阻塞等待
                                                      /* Otherwise, must wait until event occurs       */
    //置等待信号量标志
    OSTCBCur->OSTCBStat     |= OS_STAT_SEM;           /* Resource not available, pend on semaphore     */
    OSTCBCur->OSTCBStatPend  = OS_STAT_PEND_OK;
    OSTCBCur->OSTCBDly       = timeout;               /* Store pend timeout in TCB                     */
    //处理就绪组表,等待组表
    OS_EventTaskWait(pevent);                         /* Suspend task until event or timeout occurs    */
    OS_EXIT_CRITICAL();
    //进行一次调度,后进行阻塞,再次唤醒就是已经获得返回信息了
    OS_Sched();                                       /* Find next highest priority task ready         */
    //再次被唤醒,查看唤醒原因
    OS_ENTER_CRITICAL();
    switch (OSTCBCur->OSTCBStatPend) {                /* See if we timed-out or aborted                */
        case OS_STAT_PEND_OK:
             *perr = OS_ERR_NONE;
             break;//获得了信号量

        case OS_STAT_PEND_ABORT://信号量被删除
             *perr = OS_ERR_PEND_ABORT;               /* Indicate that we aborted                      */
             break;

        case OS_STAT_PEND_TO://等待超时
        default:
             OS_EventTaskRemove(OSTCBCur, pevent);
             *perr = OS_ERR_TIMEOUT;                  /* Indicate that we didn't get event within TO   */
             break;
    }
    //不管怎样,已经等待信号量,并获得了结果,需要处理目前的TCB信息
    //这个操作,就相当于,TCB请求信号量并等待,这个过程被忽略了,或者说时空穿梭,TCB请求信号量,直接就获得了结果
    //请求结果靠perr传出,此函数是正常结束,至于请求结果无所谓的
    OSTCBCur->OSTCBStat          =  OS_STAT_RDY;      /* Set   task  status to ready                   */
    OSTCBCur->OSTCBStatPend      =  OS_STAT_PEND_OK;  /* Clear pend  status                            */
    OSTCBCur->OSTCBEventPtr      = (OS_EVENT  *)0;    /* Clear event pointers                          */
#if (OS_EVENT_MULTI_EN > 0u)
    OSTCBCur->OSTCBEventMultiPtr = (OS_EVENT **)0;
#endif
    OS_EXIT_CRITICAL();

    OS_TRACE_SEM_PEND_EXIT(*perr);
}


/*
*********************************************************************************************************
*                                    ABORT WAITING ON A SEMAPHORE(中止等待一个信号量)
*
* Description: This function aborts & readies any tasks currently waiting on a semaphore.  This function
*              should be used to fault-abort the wait on the semaphore, rather than to normally signal
*              the semaphore via OSSemPost().
*该函数中止并就绪当前正在等待某一信号量的所有任务。 此函数应该用来中止在等待过程中出现故障的任务,而不是正常的因为OSSemPost()提交一个信号量而被中止等待的任务
* Arguments  : pevent        is a pointer to the event control block associated with the desired
*                            semaphore.
*指向我们希望的信号量的ECB的指针
*              opt           determines the type of ABORT performed:
*                            OS_PEND_OPT_NONE         ABORT wait for a single task (HPT) waiting on the
*                                                     semaphore,中止等待最高优先级的任务
*                            OS_PEND_OPT_BROADCAST    ABORT wait for ALL tasks that are  waiting on the
*                                                     semaphore,中止等待所有优先级的任务
*
*              perr          is a pointer to where an error message will be deposited.  Possible error
*                            messages are:
*
*                            OS_ERR_NONE         No tasks were     waiting on the semaphore.
*                            OS_ERR_PEND_ABORT   At least one task waiting on the semaphore was readied
*                                                and informed of the aborted wait; check return value
*                                                for the number of tasks whose wait on the semaphore
*                                                was aborted.
*                            OS_ERR_EVENT_TYPE   If you didn't pass a pointer to a semaphore.
*                            OS_ERR_PEVENT_NULL  If 'pevent' is a NULL pointer.
*
* Returns    : == 0          if no tasks were waiting on the semaphore, or upon error.没有任务在等待信号量,或者出现了以上错误
*              >  0          if one or more tasks waiting on the semaphore are now readied and informed.如果有任务在等待信号量,返回被唤醒的任务数
*********************************************************************************************************
*/

//是否允许中止信号量等待
#if OS_SEM_PEND_ABORT_EN > 0u
INT8U  OSSemPendAbort (OS_EVENT  *pevent,
                       INT8U      opt,
                       INT8U     *perr)
{
    INT8U      nbr_tasks;//number of tasks
#if OS_CRITICAL_METHOD == 3u                          /* Allocate storage for CPU status register      */
    OS_CPU_SR  cpu_sr = 0u;
#endif


#ifdef OS_SAFETY_CRITICAL
    if (perr == (INT8U *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return (0u);
    }
#endif

//参数检查
#if OS_ARG_CHK_EN > 0u
    if (pevent == (OS_EVENT *)0) {                    /* Validate 'pevent'                             */
        *perr = OS_ERR_PEVENT_NULL;
        return (0u);
    }
#endif
//检查ECB类型是否为信号量
    if (pevent->OSEventType != OS_EVENT_TYPE_SEM) {   /* Validate event block type                     */
        *perr = OS_ERR_EVENT_TYPE;
        return (0u);
    }
    OS_ENTER_CRITICAL();//进入临界区
    if (pevent->OSEventGrp != 0u) {                   /* See if any task waiting on semaphore?         */
        nbr_tasks = 0u;//赋初值为0
        switch (opt) {
            case OS_PEND_OPT_BROADCAST:               /* Do we need to abort ALL waiting tasks?        */
                 while (pevent->OSEventGrp != 0u) {   /* Yes, ready ALL tasks waiting on semaphore     */
                     (void)OS_EventTaskRdy(pevent, (void *)0, OS_STAT_SEM, OS_STAT_PEND_ABORT);//任务被强制中止
                     nbr_tasks++;
                 }
                 break;

            case OS_PEND_OPT_NONE:
            default:                                  /* No,  ready HPT       waiting on semaphore     */
                 (void)OS_EventTaskRdy(pevent, (void *)0, OS_STAT_SEM, OS_STAT_PEND_ABORT);
                 nbr_tasks++;
                 break;
        }
        OS_EXIT_CRITICAL();
        //有任务被唤醒了,进行一次调度
        OS_Sched();                                   /* Find HPT ready to run                         */
        *perr = OS_ERR_PEND_ABORT;
        return (nbr_tasks);//返回被唤醒的任务数
    }
    OS_EXIT_CRITICAL();//退出临界区,开中断
    *perr = OS_ERR_NONE;
    return (0u);                                      /* No tasks waiting on semaphore                 */
}
#endif


/*
*********************************************************************************************************
*                                         POST TO A SEMAPHORE(提交一个信号量)
*
* Description: This function signals a semaphore
*这个函数被用来增加一个信号量
* Arguments  : pevent        is a pointer to the event control block associated with the desired
*                            semaphore.
*指向所期待的信号量的ECB的指针
* Returns    : OS_ERR_NONE         The call was successful and the semaphore was signaled.
*              OS_ERR_SEM_OVF      If the semaphore count exceeded its limit. In other words, you have
*                                  signaled the semaphore more often than you waited on it with either
*                                  OSSemAccept() or OSSemPend().
如果信号量的数量超出了限制,换句话说,你提交了过多的信号量,已经远远的超过OSSemAccept() 或者 OSSemPend()的请求速率
*              OS_ERR_EVENT_TYPE   If you didn't pass a pointer to a semaphore
*              OS_ERR_PEVENT_NULL  If 'pevent' is a NULL pointer.
*********************************************************************************************************
*/

INT8U  OSSemPost (OS_EVENT *pevent)
{
#if OS_CRITICAL_METHOD == 3u                          /* Allocate storage for CPU status register      */
    OS_CPU_SR  cpu_sr = 0u;
#endif

//参数检查
#if OS_ARG_CHK_EN > 0u
    if (pevent == (OS_EVENT *)0) {                    /* Validate 'pevent'                             */
        return (OS_ERR_PEVENT_NULL);
    }
#endif

    OS_TRACE_SEM_POST_ENTER(pevent);
//检查ECB的类型
    if (pevent->OSEventType != OS_EVENT_TYPE_SEM) {   /* Validate event block type                     */
        OS_TRACE_SEM_POST_EXIT(OS_ERR_EVENT_TYPE);
        return (OS_ERR_EVENT_TYPE);
    }
    OS_ENTER_CRITICAL();//进入临界区,关中断
    //如果有任务在等待信号量,则直接唤醒任务
    if (pevent->OSEventGrp != 0u) {                   /* See if any task waiting for semaphore         */
                                                      /* Ready HPT waiting on event                    */
        (void)OS_EventTaskRdy(pevent, (void *)0, OS_STAT_SEM, OS_STAT_PEND_OK);
        OS_EXIT_CRITICAL();
        //退出临界区,并进行一次调度
        OS_Sched();                                   /* Find HPT ready to run                         */
        OS_TRACE_SEM_POST_EXIT(OS_ERR_NONE);
        return (OS_ERR_NONE);
    }
    //如果信号量的值小于2**16,则将信号量的值加一
    //其实我感觉是达不到这个数值的,因为一开始就设置了信号量的初始值,请求的话就会减一,只有恢复的时候会加一,但是恢复函数,比如这个函数,不会被随意调用。
    if (pevent->OSEventCnt < 65535u) {                /* Make sure semaphore will not overflow         */
        pevent->OSEventCnt++;                         /* Increment semaphore count to register event   */
        OS_EXIT_CRITICAL();
        OS_TRACE_SEM_POST_EXIT(OS_ERR_NONE);
        return (OS_ERR_NONE);
    }
    OS_EXIT_CRITICAL();                               /* Semaphore value has reached its maximum       */
    OS_TRACE_SEM_POST_EXIT(OS_ERR_SEM_OVF);
    //返回信号量数值溢出
    return (OS_ERR_SEM_OVF);
}


/*
*********************************************************************************************************
*                                          QUERY A SEMAPHORE(查询一个信号量)
*
* Description: This function obtains information about a semaphore
*这个函数用来获得一个信号量的信息
* Arguments  : pevent        is a pointer to the event control block associated with the desired
*                            semaphore
*是一个指向所期待的信号量的ECB的指针
*              p_sem_data    is a pointer to a structure that will contain information about the
*                            semaphore.
*指向用来保存信号量的结构体的指针
* Returns    : OS_ERR_NONE         The call was successful and the message was sent
*              OS_ERR_EVENT_TYPE   If you are attempting to obtain data from a non semaphore.
*              OS_ERR_PEVENT_NULL  If 'pevent'     is a NULL pointer.
*              OS_ERR_PDATA_NULL   If 'p_sem_data' is a NULL pointer
*********************************************************************************************************
*/

//是否允许信号量查询
#if OS_SEM_QUERY_EN > 0u
INT8U  OSSemQuery (OS_EVENT     *pevent,
                   OS_SEM_DATA  *p_sem_data)
{
    INT8U       i;
    OS_PRIO    *psrc;
    OS_PRIO    *pdest;
#if OS_CRITICAL_METHOD == 3u                               /* Allocate storage for CPU status register */
    OS_CPU_SR   cpu_sr = 0u;
#endif


//参数检查
#if OS_ARG_CHK_EN > 0u
    if (pevent == (OS_EVENT *)0) {                         /* Validate 'pevent'                        */
        return (OS_ERR_PEVENT_NULL);
    }
    if (p_sem_data == (OS_SEM_DATA *)0) {                  /* Validate 'p_sem_data'                    */
        return (OS_ERR_PDATA_NULL);
    }
#endif
//检查是否为信号量类型的ECB
    if (pevent->OSEventType != OS_EVENT_TYPE_SEM) {        /* Validate event block type                */
        return (OS_ERR_EVENT_TYPE);
    }
    OS_ENTER_CRITICAL();//进入临界区,关中断
    //复制等待组
    p_sem_data->OSEventGrp = pevent->OSEventGrp;           /* Copy message mailbox wait list           */
    psrc                   = &pevent->OSEventTbl[0];
    pdest                  = &p_sem_data->OSEventTbl[0];
    //复制等待表
    for (i = 0u; i < OS_EVENT_TBL_SIZE; i++) {
        *pdest++ = *psrc++;
    }
    //复制信号量的数目
    p_sem_data->OSCnt = pevent->OSEventCnt;                /* Get semaphore count                      */
    OS_EXIT_CRITICAL();
    return (OS_ERR_NONE);
}
#endif                                                     /* OS_SEM_QUERY_EN                          */


/*
*********************************************************************************************************
*                                            SET SEMAPHORE(设置一个信号量)
*
* Description: This function sets the semaphore count to the value specified as an argument.  Typically,
*              this value would be 0.
*这个函数被用来设置信号量的信号数目,一般来说,这个值通常是零
*              You would typically use this function when a semaphore is used as a signaling mechanism
*              and, you want to reset the count value.
*当将信号量用作信号传递机制并且您想重置计数值时,通常会使用此功能。
* Arguments  : pevent     is a pointer to the event control block
*指向ECB的指针
*              cnt        is the new value for the semaphore count.  You would pass 0 to reset the
*                         semaphore count.
*信号量设置的新的值,如果你想重置信号量的值,你需要传递0作为参数
*              perr       is a pointer to an error code returned by the function as follows:
*
*                            OS_ERR_NONE          The call was successful and the semaphore value was set.
*                            OS_ERR_EVENT_TYPE    If you didn't pass a pointer to a semaphore.
*                            OS_ERR_PEVENT_NULL   If 'pevent' is a NULL pointer.
*                            OS_ERR_TASK_WAITING  If tasks are waiting on the semaphore.
*********************************************************************************************************
*/

//是否允许设置信号量的值
#if OS_SEM_SET_EN > 0u
void  OSSemSet (OS_EVENT  *pevent,
                INT16U     cnt,
                INT8U     *perr)
{
#if OS_CRITICAL_METHOD == 3u                          /* Allocate storage for CPU status register      */
    OS_CPU_SR  cpu_sr = 0u;
#endif



#ifdef OS_SAFETY_CRITICAL
    if (perr == (INT8U *)0) {
        OS_SAFETY_CRITICAL_EXCEPTION();
        return;
    }
#endif
//参数检查
#if OS_ARG_CHK_EN > 0u
    if (pevent == (OS_EVENT *)0) {                    /* Validate 'pevent'                             */
        *perr = OS_ERR_PEVENT_NULL;
        return;
    }
#endif
//检查ECB的类型
    if (pevent->OSEventType != OS_EVENT_TYPE_SEM) {   /* Validate event block type                     */
        *perr = OS_ERR_EVENT_TYPE;
        return;
    }
    OS_ENTER_CRITICAL();//进入临界区,关中断
    *perr = OS_ERR_NONE;
    //如果有任务在等待信号量,则禁止更改信号量的值
    if (pevent->OSEventCnt > 0u) {                    /* See if semaphore already has a count          */
        pevent->OSEventCnt = cnt;                     /* Yes, set it to the new value specified.       */
    } else {                                          /* No                                            */
        if (pevent->OSEventGrp == 0u) {               /*      See if task(s) waiting?                  */
            pevent->OSEventCnt = cnt;                 /*      No, OK to set the value                  */
        } else {
            *perr              = OS_ERR_TASK_WAITING;
        }
    }
    OS_EXIT_CRITICAL();
}
#endif

#endif                                                /* OS_SEM_EN                                     */

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值