Deadlock occurs in Function Scoped Static variables (Thread Unsafe in VC++)
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Deadlock occurs in Function Scoped Static variables (Thread Unsafe in VC++)

Threaded View

  1. #1
    Join Date
    Feb 2010
    Posts
    1

    Angry Deadlock occurs in Function Scoped Static variables (Thread Unsafe in VC++)

    The question is how function-level statics are constructed when the function is called on multiple threads?

    Problem Description: Deadlock occurs and my application doesn't get terminated. During initialization of local static variable it tries to acquire MSVCR80!_lock and never gets hold on the lock.

    Below is the calls stack and you will see that it will never get hold on the lock _mlock

    (_EXIT_LOCK1); //C:\Program Files\Microsoft Visual Studio 8\VC\crt\src\crt0dat.c

    ntdll!RtlpWaitForCriticalSection+0x132 ntdll!RtlEnterCriticalSection+0x46
    MSVCR80!_lock+0x2e MyDLL!_onexit+0x36 [f:\sp\vctools\crt_bld\self_x86\crt\src\atonexit.c @ 103] MyDLL!atexit+0x9 [f:\sp\vctools\crt_bld\self_x86\crt\src\atonexit.c @ 127] MyDLL!__DllMainCRTStartup+0x7a [f:\sp\vctools\crt_bld\self_x86\crt\src\crtdll.c @ 498] MyDLL!_DllMainCRTStartup+0x1d [f:\sp\vctools\crt_bld\self_x86\crt\src\crtdll.c @ 462] ntdll!LdrpCallInitRoutine+0x14

    // Code snippet below
    Code:
    void main() 
    {
    
        atexit(MyCallBack); 
        exit(0); 
    
    }
    
    void MyCallBack() 
    {
    
    // Waitingforsingleobject() // Waits until all threads are terminated
    
    }
    The EXE call DllMain with DLL_THREAD_DETACH flag and we have an explicit handling as shown below
    Code:
    BOOL APIENTRY DllMain( HANDLE, DWORD dwReason, LPVOID ) 
    {
      if(dwReason == DLL_THREAD_DETACH) 
      { 
        F1();
        F2();
      }
    }
    
    F1()
    {
    
        const static CComBSTR bstrMethod = __ FUNCTION __ ;
    
    }
    
    F2()
    {
    
        const static CComBSTR bstrMethod = __ FUNCTION __ ;
    
    }
    Is it thread safe to have local static initialization within a function. Also I noticed if static variable is once initialized before the exit() of main application I don't see any problem. Can any one please explain what might be issue?

    Note: But when I make static variable as non static the deadlock doesn't occur and problem is solved.

    Also let me know any alternate solution which might help in this situation Eagerly waiting for reply.
    Last edited by cilu; February 26th, 2010 at 08:26 AM. Reason: code tags

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center