Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Deadlock occurs in Function Scoped Static variables (Thread Unsafe in

irfan074irfan074 Member Posts: 1

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 FilesMicrosoft Visual Studio 8VCcrtsrccrt0dat.c

ntdll!RtlpWaitForCriticalSection+0x132 ntdll!RtlEnterCriticalSection+0x46
MSVCR80!_lock+0x2e MyDLL!_onexit+0x36 [f:spvctoolscrt_bldself_x86crtsrcatonexit.c @ 103]
MyDLL!atexit+0x9 [f:spvctoolscrt_bldself_x86crtsrcatonexit.c @ 127]
MyDLL!__DllMainCRTStartup+0x7a [f:spvctoolscrt_bldself_x86crtsrccrtdll.c @ 498]
MyDLL!_DllMainCRTStartup+0x1d [f:spvctoolscrt_bldself_x86crtsrccrtdll.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.

Sign In or Register to comment.