rtthread 主动挂起(SUSPEND)线程
一、挂起其他线程
/** 程序清单:创建、启动、挂起、恢复线程** 这个例子会创建两个动态线程:tid1和tid2有相同的优先级,tid1线程中因无delay延时,start后tid1始终处于READY态,也正是因为这个前提,tid2才能够成功将tid1挂起。* 现象:每隔20s(200ms*100),tid1被tid2挂起或恢复一次。*/
rt_thread_t my_tid1 = RT_NULL, my_tid2 = RT_NULL;void my_tid1_thread_entry(void* params)
{
int cnt = 0;rt_kprintf("enter my_tid1, priority = %d, status=%d\n", my_tid1->current_priority, my_tid1->stat);while(1){
cnt++;if(cnt%1000000 == 0)rt_kprintf("this is my_tid1, cnt = %d\n", cnt);}
}void my_tid2_thread_entry(void* params)
{
int cnt = 0, ret = 0;rt_kprintf("enter my_tid2, priority = %d, status=%d\n", my_tid2->current_priority, my_tid2->stat);while(1){
cnt++;rt_kprintf("this is my_tid2, cnt = %d\n", cnt);rt_thread_mdelay(200);if(cnt%100 == 0){
if(my_tid1->stat == RT_THREAD_SUSPEND){
ret = rt_thread_resume(my_tid1); rt_kprintf("============resume tid1 ret=%d ============\n",ret);}else if(my_tid1->stat == RT_THREAD_READY){
ret = rt_thread_suspend(my_tid1);rt_kprintf("============suspend tid1 ret=%d ============\n",ret);}}}
}void suspend_resume_test(int argc, char* argv[])
{
if(RT_NULL == my_tid1){
my_tid1 = rt_thread_create("my_tid1", my_tid1_thread_entry, NULL, THREAD_STACK_SIZE, RT_THREAD_PRIORITY_MAX - 4, THREAD_TIMESLICE);if(RT_NULL != my_tid1)rt_thread_startup(my_tid1);}if(RT_NULL == my_tid2){
my_tid2 = rt_thread_create("my_tid2", my_tid2_thread_entry, NULL, THREAD_STACK_SIZE, RT_THREAD_PRIORITY_MAX - 4, THREAD_TIMESLICE);if(RT_NULL != my_tid2)rt_thread_startup(my_tid2);}
}
MSH_CMD_EXPORT(suspend_resume_test, suspend_resume_test);
二、挂起自身线程
通常不应该使用rt_err_t rt_thread_suspend(rt_thread_t thread)来挂起线程本身,如果确实需要采用 rt_thread_suspend() 函数挂起当前任务,需要在调用 rt_thread_suspend() 函数后立刻调用 rt_schedule() 函数进行手动的线程上下文切换。只需要了解,不推荐使用。