星期五, 十二月 15, 2006

If a function have more than one exit, we must prevent reentered.

Today I find a bug in my codes. The bug is caused by that a function has been reentered. The function's structure looks like this:

void foo()
{
while(true){
// give a chance to handle message
if(true == PeekMessage(...)){
...
TranslateMessage(...);
DispatchMessage(...);
...
}

// do other things
...
}
}

In the above codes, we give a chance to handle messages in foo(), so there is another exit of this function. And the message's handler maybe call foo() again. If is it, the foo() function will be reentered. That means the function would be called again, even the first call doesn't finished. So if a function have more than one exit, we must prevent reentered. See the updated code:

void foo()
{
static bFinished = true;

if(!bFinished)
return;

bFinished = false;

while(true){
// give a chance to handle message
if(true == PeekMessage(...)){
...
TranslateMessage(...);
DispatchMessage(...);
...
}

// do other things
...
}

bFinished = true;
}

0 评论: