自定义任务状态来操作FreeRTOS任务的挂起,恢复,删除

osThreadState osState2;//自定义一个线程的状态

osThreadState 系统枚举定义如下:
typedef enum {
    osThreadRunning   = 0x0,          /* A thread is querying the state of itself, so must be running. */
    osThreadReady     = 0x1 ,                    /* The thread being queried is in a read or pending ready list. */
    osThreadBlocked   = 0x2,                /* The thread being queried is in the Blocked state. */
    osThreadSuspended = 0x3,          /* The thread being queried is in the Suspended state, or is in the Blocked state with an infinite time out. */
    osThreadDeleted   = 0x4,                  /* The thread being queried has been deleted, but its TCB has not yet been freed. */   
  osThreadError     = 0x7FFFFFFF
} osThreadState;

如果用系统查询任务状态函数查找线程状态
osState2 = osThreadGetState(myTask02Handle);
查询到的状态osState2 = osThreadBlocked等于阻塞的情况很容易出现
在这种情况下来操作线程的创建,删除,挂起,恢复容易导致程序崩溃

osThreadState osState2程序里我们不使用osThreadGetState来查询线程的状态
而是在自己的程序里来赋值,比如创建完任务后osState2 = osThreadRunning;
删除完任务后osState2 = osThreadDeleted;
挂起任务后osState2 = osThreadSuspended;
恢复完任务后osState2 = osThreadRunning;
这样任务的状态始终只有三个状态osThreadDeleted,osThreadSuspended,osThreadRunning。

if(strcmp(ppara1,"任务挂起2") == 0)//收到挂起的命令
{
    if(osState2 == osThreadRunning)//如果任务是运行状态,才会执行挂起动作
    {
        if(osOK == osThreadSuspend(myTask02Handle))//如果任务挂起成功
        {
            osState2 = osThreadSuspended;//则改变任务2的状态为挂起
            printf("任务2已经挂起\r\n");
        }
    }    
}
else if(strcmp(ppara1,"任务恢复2") == 0)//收到恢复的命令
{
    if(osState2 == osThreadSuspended)//如果任务是挂起状态,才执行任务恢复动作
    {
        if(osOK ==osThreadResume(myTask02Handle))//如果任务挂起成功
        {
            osState2 = osThreadRunning;//则改变任务2的状态为运行
            printf("任务2已经恢复\r\n");
        }    
    }
}
else if(strcmp(ppara1,"任务删除2") == 0)//收到删除的命令
{
    if(osState2 != osThreadDeleted)//如果任务不是删除状态,才执行任务删除动作
    {
        if(osOK == osThreadTerminate(myTask02Handle))//如果任务删除成功
        {
            osState2 = osThreadDeleted;//则改变任务2的状态为删除
            printf("任务2已经删除\r\n");
        }
    }    
}
else if(strcmp(ppara1,"任务创建2") == 0)//收到创建的命令
{
    if(osState2 == osThreadDeleted)//如果任务是删除状态,才执行任务创建动作
    {
        osThreadDef(myTask02, StartTask02, osPriorityIdle, 0, 128);
        myTask02Handle = osThreadCreate(osThread(myTask02), NULL);//创建任务
        osState2 = osThreadRunning;//则改变任务2的状态为运行
        printf("任务2已经创建\r\n");
    }    
}

 

posted @ 2019-09-16 16:10  阿坦  阅读(1730)  评论(0编辑  收藏  举报