When is a divide by zero not a divide by zero? A puzzle in the debugger (static variable issues)

后端 未结 2 2004
面向向阳花
面向向阳花 2020-12-11 01:02

I\'m very confused and I think my debugger is lying to me. I have the following loop in my code:

MyClass::UploadFile(CString strFile)
{
  ...
  static DWORD         


        
2条回答
  •  粉色の甜心
    2020-12-11 01:58

    The problem may be related to multithreading.

    1. A thread enters the function
    2. Checks the hidden "is_initialized" static variable to see if initialization has already been performed
    3. The var is 0, so it sets the variable to 1 and proceeds reading the registry
    4. At this point another thread enters the function
    5. The second thread sees the variables as already initialized and skips the initialization code
    6. The division is performed when the denominator is still 0 (the first thread is still reading the registry)
    7. The program crashes, but in the meanwhile the first thread completes execution, setting the variables that you see in the dump.
    8. You lose sleep thinking how the impossible happened

提交回复
热议问题