1 /* 2 * 程序清单:静态信号量 3 * 4 * 这个例子中将创建一个静态信号量(初始值为0 )及一个静态线程,在这个静态线程中 5 * 将试图采用超时方式去持有信号量,应该超时返回。然后这个线程释放一次信号量,并 6 * 在后面继续采用永久等待方式去持有信号量, 成功获得信号量后返回。 7 */ 8 #include <rtthread.h> 9 #include "tc_comm.h" 10 11 /* 线程控制块及栈 */ 12 static struct rt_thread thread; 13 static rt_uint8_t thread_stack[THREAD_STACK_SIZE]; 14 /* 信号量控制块 */ 15 static struct rt_semaphore sem; 16 17 /* 线程入口 */ 18 static void thread_entry(void* parameter) 19 { 20 rt_err_t result; 21 rt_tick_t tick; 22 23 /* 获得当前的OS Tick */ 24 tick = rt_tick_get(); 25 26 /* 试图持有信号量,最大等待10个OS Tick后返回 */ 27 result = rt_sem_take(&sem, 10); 28 if (result == -RT_ETIMEOUT) 29 { 30 rt_tick_t new_tick = rt_tick_get(); 31 /* 可以有两个 tick 的误差 */ 32 if (new_tick - tick >= 12) 33 { 34 rt_kprintf("tick error to large: expect: 10, get %d\n", 35 new_tick - tick); 36 37 tc_done(TC_STAT_FAILED); 38 rt_sem_detach(&sem); 39 return; 40 } 41 rt_kprintf("take semaphore timeout\n"); 42 } 43 else 44 { 45 /* 因为没有其他地方是否信号量,所以不应该成功持有信号量,否则测试失败 */ 46 tc_done(TC_STAT_FAILED); 47 rt_sem_detach(&sem); 48 return; 49 } 50 51 /* 释放一次信号量 */ 52 rt_sem_release(&sem); 53 54 /* 永久等待方式持有信号量 */ 55 result = rt_sem_take(&sem, RT_WAITING_FOREVER); 56 if (result != RT_EOK) 57 { 58 /* 不成功则测试失败 */ 59 tc_done(TC_STAT_FAILED); 60 rt_sem_detach(&sem); 61 return; 62 } 63 64 /* 测试通过 */ 65 tc_done(TC_STAT_PASSED); 66 /* 脱离信号量对象 */ 67 rt_sem_detach(&sem); 68 } 69 70 int semaphore_static_init(void) 71 { 72 rt_err_t result; 73 74 /* 初始化信号量,初始值是0 */ 75 result = rt_sem_init(&sem, "sem", 0, RT_IPC_FLAG_FIFO); 76 if (result != RT_EOK) 77 { 78 tc_stat(TC_STAT_END | TC_STAT_FAILED); 79 return 0; 80 } 81 82 /* 初始化线程1 */ 83 result = rt_thread_init(&thread, "thread", /* 线程名:thread */ 84 thread_entry, RT_NULL, /* 线程的入口是thread_entry,入口参数是RT_NULL*/ 85 &thread_stack[0], sizeof(thread_stack), /* 线程栈是thread_stack */ 86 THREAD_PRIORITY, 10); 87 if (result == RT_EOK) /* 如果返回正确,启动线程1 */ 88 rt_thread_startup(&thread); 89 else 90 tc_stat(TC_STAT_END | TC_STAT_FAILED); 91 92 return 0; 93 } 94 95 #ifdef RT_USING_TC 96 static void _tc_cleanup(void) 97 { 98 /* 调度器上锁,上锁后,将不再切换到其他线程,仅响应中断 */ 99 rt_enter_critical(); 100 101 /* 执行线程脱离 */ 102 if (thread.stat != RT_THREAD_CLOSE) 103 { 104 rt_thread_detach(&thread); 105 106 /* 执行信号量对象脱离 */ 107 rt_sem_detach(&sem); 108 } 109 110 /* 调度器解锁 */ 111 rt_exit_critical(); 112 113 /* 设置TestCase状态 */ 114 tc_done(TC_STAT_PASSED); 115 } 116 117 int _tc_semaphore_static(void) 118 { 119 /* 设置TestCase清理回调函数 */ 120 tc_cleanup(_tc_cleanup); 121 semaphore_static_init(); 122 123 /* 返回TestCase运行的最长时间 */ 124 return 100; 125 } 126 /* 输出函数命令到finsh shell中 */ 127 FINSH_FUNCTION_EXPORT(_tc_semaphore_static, a static semaphore example); 128 #else 129 /* 用户应用入口 */ 130 int rt_application_init(void) 131 { 132 semaphore_static_init(); 133 134 return 0; 135 } 136 #endif 137