This topic is 4611 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Im beginning to think threads don't work in the way I think they do. Anyway, I have the main program thread and another thread to load thumbnails. If the user changes directory the following function is called:
bool EndThumbThread()
{
{
}
return 0;
}


Thread number two sets global int Thread2Status to one when it is called. It then loads each thumbnail and checks the global bool CancelThread. If true it exits. When it exists (either because of that or its just finished) it sets Thread2Status to 0. Thhis works fine in Debug mode or Release without optimizations. But with optimizations the veriables work as though they are not the same! The thumb thread refuses to exit until its finished, and when it is Thread2Status is not set to 0. (The instruction to do so is def executed). The obvious result is the program hangs. I got a read out of the address of these veriables from each context and they match. I can fix this problem by disabling optimizations. But I want to know whats gone wrong? Can anyone help, Ta!

##### Share on other sites
Did you declare the variable volatile?

Though it would probably be more robust to use event objects or some other more normal thread synchronization methd,.

##### Share on other sites
Quote:
 Original post by SiCraneDid you declare the variable volatile?Though it would probably be more robust to use event objects or some other more normal thread synchronization methd,.

Bingo! Works, thanks for that.

Ill have to look that up and see what it does! Is my methord perticularly bad or just unorthodox?(which all my code is)

ETA: MSDN tels me what its for. Im starting to understand it. But what happens to veriables not declared with volatile in the situation ive discribed above?

##### Share on other sites
Each thread gets it's own copy in it's own registers. Volatile does little more than disable optimizations that aren't safe when threading.

##### Share on other sites
What your code does is called busy waiting. It keeps the thread active the whole time it waits for the change in the variable. This is inefficient; it's best to let the thread sleep while the other thread does its thing. So if you waited on an event object instead of polling the variable, things would probably work better since it would yield control to the other thread. You could probably get some improvement just by calling Sleep() in your polling loop.

Anyways, probably what happens when optimizations is that the compiler will do value propogation on the Thread2Status. It knows going into the while loop that Thread2Status is 1. So it optimizes the while loop into while(true). volatile tells the compiler that the data flow may be broken so it has to actually read the memory every time it tests.