I have a DLL which is used by an ATL-COM component. Inside my DLL, a method StartMonitoring gets called from FinalConstruct. I want to create background thread inside StartMonitoring(), but the thread is created and a valid handle is returned yet the code inside the thread never gets executed. Does this have to do something with the way ATL components work? Please excuse me if its a dumb question but i do not have any ATL/COM understanding.
Here i believe it has something to with the way COM works. In my case i need StartMonitoring to start a background thread and when StopMonitoring is called from FinalRelease() will signal this background thread to quit and then Wait for it to quit. Now because the Thread is not started but have given a valid handle, StopMonitoring will signal and wait for ever. If i forcibly end StopMonitoring by bypassing Wait and return to FinalRelease(), MonitorThreadProc then starts execution.
unsigned int WINAPI CMonitor::MonitorThreadProc(LPVOID lpvParam)
{
std::cout << "Enter MonitorThreadProc" << endl; //Never hits this
if (lpvParam == nullptr)
return 1;
CMonitor *pMonitor = static_cast<CMonitor*>(lpvParam);
return (unsigned int)pMonitor->Run();
}
void CMonitor::StopMonitoring()
{
if(m_EvtReg)
{
m_EvtStopMonitoring.Set();
DWORD dwResult = ::WaitForSingleObject(m_hThread, INFINITE);
if(dwResult == WAIT_OBJECT_0)
{
cout<<"Thread terminated"<<endl;
}
}
m_EvtReg.Close();
m_EvtStopMonitoring.Close();
HANDLE h = m_hThread.Detach();
CloseHandle(h);
}
bool CMonitor::StartMonitoring()
{
int num = 0;
unsigned int nThreadId = 0;
HANDLE hThread = (HANDLE)_beginthreadex(nullptr, 0, MonitorThreadProc, (LPVOID)this, 0, &nThreadId);
if(hThread == nullptr)
{
return false;
}
//I get a valid handle from _beginthreadex, but the thread never gets executed.
m_hThread.Attach(hThread);
return true;
}
The odd behaviour was due to the loader lock held during the DLL load . Until the loader lock is held , thread is never scheduled and hence I was not seeing the code execution.