Re: mutex question
- From: David Jones <ncic@xxxxxxxxxx>
- Date: Sun, 30 Apr 2006 15:36:15 -0500
Stealer wrote:
// ???? while(x); <> while(x) { statements} ???
// VC Compiler bug in Release configuration
[...snip...]
continue_flag = 1;
CreateThread(NULL, 0, ThreadProc, 0, 0, 0);
while (continue_flag)
{
//printf("You : I love you, Bill\n"); // you can not exit this program
if remove this line.
};
[...snip...]
// Note: You must buid in Release to find out the problem
// Disassembly:
// 00401048 jmp 00401048
// --> no compare before jmp
This is not a compiler bug -- this is a code bug. The continue_flag
variable should be declared as volatile since it can be modified by
another thread. Since you're not changing continue_flag in the loop,
it is perfectly valid for the compiler to optimize the check away
completely.
This is why the 'volatile' keyword exists -- to tell the compiler
that a variable can change unexpectedly, such as when it is shared
between threads. Today's compilers are smart, but they can't read
your mind (yet). :)
Why does it not optimize the check away when a call to printf is in
the loop? Maybe since it's a global variable and you're calling a
function in another compilation unit, it thinks that the variable
might be extern'ed and potentially modified by that function. I'd
bet that if you replaced the statement with, say, setting the value
of a local variable, you'd get the optimized code -- just jmp. (It
would probably move the assignment out of the loop.)
Long story short: use 'volatile' on variables shared between threads.
David
.
- Follow-Ups:
- Re: mutex question
- From: Tom Widmer [VC++ MVP]
- Re: mutex question
- From: anton bassov
- Re: mutex question
- Prev by Date: Re: Help me for a typical problem regarding KeAquireSpinLock which is not Locking other Thread in Same CPU
- Next by Date: Re: Help me for a typical problem regarding KeAquireSpinLock which is not Locking other Thread in Same CPU
- Previous by thread: Re: Help me for a typical problem regarding KeAquireSpinLock which is not Locking other Thread in Same CPU
- Next by thread: Re: mutex question
- Index(es):
Relevant Pages
|
Loading