;/**************************************************************************************
;* 函数名称: OSIntCtxSw
;*
;* 功能描述: 中断级任务切换
;*
;* 参    数: None
;*
;* 返 回 值: None
;***************************************************************************************/
OSIntCtxSw
  PUSH    {R4, R5}
        LDR     R4, =NVIC_INT_CTRL      ;触发PendSV异常 (causes context switch)
        LDR     R5, =NVIC_PENDSVSET
        STR     R5, [R4]
  POP     {R4, R5}
        BX      LR
        NOP
;/**************************************************************************************
;* 函数名称: OSPendSV
;*
;* 功能描述: OSPendSV is used to cause a context switch.
;*
;* 参    数: None
;*
;* 返 回 值: None
;***************************************************************************************/
PendSV_Handler
        CPSID   I                                   ; Prevent interruption during context switch
        MRS     R0, PSP                             ; PSP is process stack pointer 如果在用PSP堆栈,则可以忽略保存寄存器,参考CM3权威中的双堆栈-白菜注
        CBZ     R0, PendSV_Handler_Nosave           ; Skip register save the first time
        SUBS    R0, R0, #0x20         
        STM     R0, {R4-R11}                        ; Save remaining regs r4-11 on process stack
        LDR     R1, =OSCurTCB    
        LDR     R1, [R1]
        STR     R0, [R1]                             ; R0 is SP of process being switched out          
PendSV_Handler_Nosave
        PUSH    {R14}                                ; Save LR exc_return value
        LDR     R0, =OSTaskSwHook                    ; OSTaskSwHook();
        BLX     R0
        POP     {R14}
        LDR     R0, =OSCurTCB                         ;OSCurTCB=OSNewTCB;     
        LDR     R1, =OSNewTCB
        LDR     R2, [R1]
        STR     R2, [R0]
        LDR     R0, [R2]                              ; R0 is new process SP; SP = OSCurTCB;       
        LDM     R0, {R4-R11}                ; Restore r4-11 from new process stac
        ADD     R0, R0, #0x20
        MSR     PSP, R0             
        ORR     LR, LR, #0x04
  CPSIE   I                                 ; Exception return will restore remaining context
        BX      LR                   
  end

  接下来定义一个任务控制块:

typedef struct taskControlBlock
{
 /*当前的栈顶指针*/
 OS_STK     *pStackTop;
 /*当前优先级*/
 PRIO_TYPE    CurPriority;
 /*任务状态*/
 uint8      TaskStat;
 /*等待时间片的个数*/
 int32     TCBDelay;
 
} TCB;
/*当前运行的任务*/
TCB   *OSCurTCB;
/*当前准备新运行的任务*/
TCB   *OSNewTCB;
/*当前OS中所有的任务*/
uint8  TaskNUM=0;
TCB   OSTCBTable[MAX_TASK_NUM];