example of a infinityloop by optimization(done by the compiler) in C++ in Visual Studio2010

I have to do a demonstration of how the compiler produces a infinity-loop while optimizing a program.

I have to show it in C++ in Visual Studio 2010 and I think he best way to show it is with and without volatile.

I used the code from here http://msdn.microsoft.com/en-us/library/12a04hfd%28v=vs.80%29.aspx and tried it with and without volatile(and compile with: /EHsc /O2) But there is no infinity-loop. I also change it like that :

// compile with: /EHsc /O2

#include <iostream>
#include <windows.h>
using namespace std;

//volatile bool Sentinel = true;
bool Sentinel = true;
int CriticalData = 0;
int round=0;

unsigned ThreadFunc1() {
   while (Sentinel){
        Sleep(10);   // volatile spin lock   
        cout << "Critical Data = " << CriticalData << endl; 
   }
   return 0;
} 
unsigned  ThreadFunc2() {
   Sleep(2000);
   CriticalData++; 
   Sentinel = false; 
   return 0;
}

int main() {
   HANDLE hThread1, hThread2; 

   hThread1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ThreadFunc1, NULL, 0, NULL);
   hThread2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ThreadFunc2, NULL, 0, NULL);

   CloseHandle(hThread1);
   CloseHandle(hThread2);

   system("pause");
} 

But no infinity-loop. Does someone have an idea?

Answers


The compiler does not know for sure what Sleep(int) and iostream.operator <<() can do with your global variables. It's possible (from its point of view), that they can change Sentinel variable, so compiler can't remove reading of Sentinel from the loop.


What's the problem here? The compiler may produce an infinite loop without volatile, but it doesn't have to. It's more likely to see an infinite loop when compiling with highest optimization level and turning debug info off.


int gIMightBeUseful = 1;

void foo()
{
  int bar;
  while(!bar){gIMightBeUseful++;}
}

Has a chance of infinite looping depending on optimization level. Or does it have to be thread interlock specific?


Need Your Help

Input text auto width filling 100% with other elements floating

html css css-float

i have the following layout for a search box with:

Add code to both iOS/objective-C project and c++ library at once?

c++ ios objective-c c xcode

I have a usual Objective-C project and MonkSVG li which contains C++ classes.