Subj : (MFC)Multithreading : Main thread gets blocked ? What could be the reason ? To : comp.programming.threads From : ajay.sonawane Date : Thu Jun 30 2005 05:00 am Its a threading problem. Let me explain it first. I am using MFC. My GUI (main) thread creates a worker thread that does some lengthy operations using while loop. I want to keep only one worker thread alive for doing that lengthy operations. Main thread creates worker thread when it receives a user defined messages and when no thread (created eariler) is running ( I checked it by using WaitForSingleObject(hThread) ) , I am using some of member variables to abort thread and restart lengthy operation from start if list is refilled from main thread. It means that without creating new thread, I reused existing one to do lengthy operation. I have used critical section to synchronize access to some variables and operations. Here is code, LRSULT CMainFrame::OnUserMessage(WPARAM wParam,LPARAm lParam) { if(!IsThreadRunning(0)) { //thread is not running // delete old pointer and start new thread if(m_pAdvtThread) { delete m_pAdvtThread; m_pAdvtThread = NULL; } } else { TRACE("\nThread is still running !" ); m_bRestartProcessAdvts = TRUE; g_CS.Unlock(); return 1; } g_CS.Unlock(); g_CS.Lock(); // Start a worker thread to searck keyword in browsed page m_bRestartProcessAdvts = FALSE; m_bAbortProcessAdvts = FALSE; m_pAdvtThread = AfxBeginThread (AdvtThreadProc,this,THREAD_PRIORITY_LOWEST,0,CREATE_SUSPENDED); m_pAdvtThread->SetThreadPriority(THREAD_PRIORITY_LOWEST); m_pAdvtThread->m_bAutoDelete = FALSE; m_pAdvtThread->ResumeThread(); g_CS.Unlock(); } // My worker thread UINT AdvtThreadProc (LPVOID lpParam) { // Process keywords for (int i=0; i < m_pList->GetCount(); i++) { ::Sleep(10); // Abort Processing if(pMainFrame->m_bAbortProcessAdvts) { AfxEndThread(0,TRUE); } // Restart Processing if(pMainFrame->m_bRestartProcessAdvts) { g_CS.Lock(); pMainFrame->m_bRestartProcessAdvts = FALSE; g_CS.Unlock(); continue; } DoSomeLengthOperation(); AfxEndThread(1,TRUE); } bool CMainFrame::IsThreadRunning(dwTimeOut) { if(m_pAdvtThread) { if(WAIT_TIMEOUT == WaitForSingleObject( m_pAdvtThread->m_hThread,dwTimeOut)) return true; // Thread is still running } return false; } Now my problem is , Many times my main thread becomes blocked and utilized 100% CPU, I think that it happens due to some deadlock situation. I am not getting where I did wrong ? I am using Sleep(10) to sleep thread for some time so that it won't make thread busy. I used WaitForSingleObject with value 0 means it will check and return state of thread. I agree that I am using WaitForSingleObject in UI thread which is not a good idea, But That is not the problem. I think that critical section might be causing deadlocks. Please let me know the solution. .