I am using the Microsoft Visual Studio to build a program that has several threads. The threads communicate among them reading a shared variable; thus, a thread is waiting: "while (variable == 0);", until other thread puts the variable into 1. That occurs more than one time in the program, and everything works fine in the Debug version. However, the Release version does not get out from the while bucle. I have tried some changes like:

while (variable == 0)
cout << ".";

instead of the previous:

while (variable == 0);

And it works fine in this way. I would like to know why this happens, whether there is any conflict between the variables (I think that this is not a concurrency problem, since only one thread writes on the variable) or why, perhaps, the while condition is not read again and again.

Although the program works, I would like to remove all these couts. Anybody knows how I could improve this fact?

Thank you very much,


Try volatile int variable; Even then, you should really use proper synchronisation.

If the compiler sees

int variable = 0;
while (variable == 0)

the optimiser (in release builds) will see that there is no (obvious) way that variable can change, and so it optimises the code to become while ( true )

OK, Salem, it is a good explanation. Thank you.

And which synchronisation type should I use for this operation (one thread only writes and the other one only reads). Do you have any example code?

Thank you,


Read the manual - it's good practice for the future.

I think the best way to synchronize a thread that waits for another to finish doing something is a semaphore. Do you agree with me?
Is there any library in C++ to implement them? If not, could anybody give me a link to learn how to implement one?

Thank you,