المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Deadlock occurs in Function Scoped Static variables (Thread Unsafe in VC++)



C++ Programming
02-27-2010, 01:01 AM
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
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

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.irfan