RT-Thread遇到的问题—多个信号量的初始化问题
一、代码如下:
struct rt_semaphore* BLE_sem;
struct rt_semaphore* MOTOR_sem;
struct rt_semaphore* WH4G_sem;
struct rt_semaphore* VOICE_sem;`
tid = rt_sem_init(BLE_sem,"BLE_sem",0,RT_IPC_FLAG_FIFO);
if(tid!=RT_EOK) printf("BLE_sem init failed\r\n");else printf("BLE_sem init successed\r\n");
tid = rt_sem_init(MOTOR_sem,"MOTOR_sem",0,RT_IPC_FLAG_FIFO);
if(tid!=RT_EOK) printf("MOTOR_sem init failed\r\n");else printf("MOTOR_sem init successed\r\n");
tid = rt_sem_init(WH4G_sem,"WH4G_sem",0,RT_IPC_FLAG_PRIO);
if(tid!=RT_EOK) printf("WH4G_sem init failed\r\n");else printf("WH4G_sem init successed\r\n");
tid = rt_sem_init(VOICE_sem,"VOICE_sem",1,RT_IPC_FLAG_FIFO);
if(tid!=RT_EOK) printf("VOICE_sem init failed\r\n");else printf("VOICE_sem init successed\r\n");
出现的问题:现象是,我初始化一个信号量不会有问题;但是初始化多于一个信号量时,在第二个初始化的过程中,会跳转到“故障异常处理程序”中。
二、具体的解决办法如下:
/定义信号量的结构体/
struct rt_semaphore BLE_sem;
struct rt_semaphore MOTOR_sem;
struct rt_semaphore WH4G_sem;
struct rt_semaphore VOICE_sem;
tid = rt_sem_init(&BLE_sem,"BLE_sem",0,RT_IPC_FLAG_FIFO);
if(tid!=RT_EOK) printf("BLE_sem init failed!\r\n");else printf("BLE_sem init successed!\r\n");
tid = rt_sem_init(&MOTOR_sem,"MOTOR_sem",0,RT_IPC_FLAG_PRIO);
if(tid!=RT_EOK) printf("MOTOR_sem init failed!\r\n");else printf("MOTOR_sem init successed!\r\n");
tid = rt_sem_init(&WH4G_sem,"WH4G_sem",0,RT_IPC_FLAG_PRIO);
if(tid!=RT_EOK) printf("WH4G_sem init failed!\r\n");else printf("WH4G_sem init successed!\r\n");
tid = rt_sem_init(&VOICE_sem,"VOICE_sem",1,RT_IPC_FLAG_FIFO);
if(tid!=RT_EOK) printf("VOICE_sem init failed!\r\n");else printf("VOICE_sem init successed!\r\n");
三、原因分析
struct rt_semaphore* BLE_sem;语句的含义是定义了一个信号量的指针,此时是没有具体的信号量的具体空间的。就像包皮公司一样,只有一个名字,但是没有对应的办公场所和人员。
rt_sem_init(BLE_sem,“BLE_sem”,0,RT_IPC_FLAG_FIFO);此时再定义相应的信号量就会出现找不到相应结构体的问题,从而报错。
问:为什么使用struct rt_semaphore*,定义一个信号量的时候,不会报错呢。
原因:如果你跳转到struct rt_semaphore这个结构体,就会看到如下的代码:
/**
-
Semaphore structure
*/
struct rt_semaphore
{
struct rt_ipc_object parent; /**< inherit from ipc_object */rt_uint16_t value; /< value of semaphore. */
rt_uint16_t reserved; /< reserved field */
};
typedef struct rt_semaphore *rt_sem_t;
翻译一下就是,信号量已经定义了一个结构体,但是没有定义变量。
如果你使用struct rt_semaphore *或者rt_sem_t定义了一个信号量的指针,此时是有一个已经存在的信号量结构体空间供其使用,所以不会报错。
希望对大家有帮助