UINT32 引起的死循环
上周出差定位一个死循环。一个函数进行一个信号量的初始化,每次进行一次业务都要调用这个函数初始化,这个函数作用是保障初始化后信号量初始化值为SEM_INIT_NUM
,但因为UINT32
的关系出现死循环了。代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SINT32 txsem_count_init(Semaphore *ptxSem) | |
{ | |
UINT32 i = 0; | |
UINT32 semCount = 0; | |
UINT32 Count = 0; | |
semCount = GetSemaphoreCount(ptxSem); | |
Count = SEM_INIT_NUM - semCount; | |
if (Count > 0) | |
{ | |
for( i=0;i<Count;i++) | |
{ | |
PutSemaphore(ptxSem); | |
} | |
} | |
else if (Count < 0) | |
{ | |
Count = 0 - Count; | |
for(i = 0;i<Count;i++) | |
{ | |
GetSemaphore(ptxSem); | |
} | |
} | |
return SUCCESS; | |
} |
出现问题的时候,semCount
为4,而宏SEM_INIT_NUM
为3,造成Count = SEM_INIT_NUM - semCount
为-1
了,但因为Count
是UINT32
,从而变成0xFFFFFFFF
,一个极大值,造成for循环执行长时间不退出。修改方法是将Count
的UINT32
改成SINT32
。这是一个非常低级的代码错误。
其实更简单的是删除信号量,重新创建信号量,这样代码会容易读的多。
DeleteSemaphore(ptxSem);
ptxSem = CreateSemaphore(SEM_INIT_NUM);

本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。