1 /* 2 * 程序清单:线程脱离 3 * 4 * 这个例子会创建两个线程,在其中一个线程中执行对另一个线程的脱离。 5 */ 6 #include <rtthread.h> 7 #include "tc_comm.h" 8 9 /* 线程1控制块 */ 10 static struct rt_thread thread1; 11 /* 线程1栈 */ 12 static rt_uint8_t thread1_stack[THREAD_STACK_SIZE]; 13 /* 线程2控制块 */ 14 static struct rt_thread thread2; 15 /* 线程2栈 */ 16 static rt_uint8_t thread2_stack[THREAD_STACK_SIZE]; 17 18 /* 线程1入口 */ 19 static void thread1_entry(void* parameter) 20 { 21 rt_uint32_t count = 0; 22 23 while (1) 24 { 25 /* 线程1采用低优先级运行,一直打印计数值 */ 26 rt_kprintf("thread count: %d\n", count ++); 27 } 28 } 29 30 /* 线程2入口 */ 31 static void thread2_entry(void* parameter) 32 { 33 /* 线程2拥有较高的优先级,以抢占线程1而获得执行 */ 34 35 /* 线程2启动后先睡眠10个OS Tick */ 36 rt_thread_delay(10); 37 38 /* 39 * 线程2唤醒后直接执行线程1脱离,线程1将从就绪线程队列中删除 40 */ 41 rt_thread_detach(&thread1); 42 43 /* 44 * 线程2继续休眠10个OS Tick然后退出 45 */ 46 rt_thread_delay(10); 47 48 /* 49 * 线程2运行结束后也将自动被从就绪队列中删除,并脱离线程队列 50 */ 51 } 52 53 int thread_detach_init() 54 { 55 rt_err_t result; 56 57 /* 初始化线程1 */ 58 result = rt_thread_init(&thread1, "t1", /* 线程名:t1 */ 59 thread1_entry, RT_NULL, /* 线程的入口是thread1_entry,入口参数是RT_NULL*/ 60 &thread1_stack[0], sizeof(thread1_stack), /* 线程栈是thread1_stack */ 61 THREAD_PRIORITY, 10); 62 if (result == RT_EOK) /* 如果返回正确,启动线程1 */ 63 rt_thread_startup(&thread1); 64 else 65 tc_stat(TC_STAT_END | TC_STAT_FAILED); 66 67 /* 初始化线程2 */ 68 result = rt_thread_init(&thread2, "t2", /* 线程名:t2 */ 69 thread2_entry, RT_NULL, /* 线程的入口是thread2_entry,入口参数是RT_NULL*/ 70 &thread2_stack[0], sizeof(thread2_stack), /* 线程栈是thread2_stack */ 71 THREAD_PRIORITY - 1, 10); 72 if (result == RT_EOK) /* 如果返回正确,启动线程2 */ 73 rt_thread_startup(&thread2); 74 else 75 tc_stat(TC_STAT_END | TC_STAT_FAILED); 76 77 return 0; 78 } 79 80 #ifdef RT_USING_TC 81 static void _tc_cleanup() 82 { 83 /* 调度器上锁,上锁后,将不再切换到其他线程,仅响应中断 */ 84 rt_enter_critical(); 85 86 /* 执行线程脱离 */ 87 if (thread1.stat != RT_THREAD_CLOSE) 88 rt_thread_detach(&thread1); 89 if (thread2.stat != RT_THREAD_CLOSE) 90 rt_thread_detach(&thread2); 91 92 /* 调度器解锁 */ 93 rt_exit_critical(); 94 95 /* 设置TestCase状态 */ 96 tc_done(TC_STAT_PASSED); 97 } 98 99 int _tc_thread_detach() 100 { 101 /* 设置TestCase清理回调函数 */ 102 tc_cleanup(_tc_cleanup); 103 thread_detach_init(); 104 105 /* 返回TestCase运行的最长时间 */ 106 return 25; 107 } 108 /* 输出函数命令到finsh shell中 */ 109 FINSH_FUNCTION_EXPORT(_tc_thread_detach, a static thread example); 110 #else 111 /* 用户应用入口 */ 112 int rt_application_init() 113 { 114 thread_detach_init(); 115 116 return 0; 117 } 118 #endif 119