2 wangxingdezh123 wangxingdezh123 于 2014.11.05 19:39 提问

临界区 使用sleep后程序崩溃

m_list1,m_list2,是映射的两个listbox的控件变量,在sleep后崩溃,刚开始以为时间设置小了,调整到1000,还是崩溃,敬请各位大牛指点小弟。。。。。。
代码如下:
int nTiecks =30;
HANDLE hthread1,hthread2;
CRITICAL_SECTION cs;

DWORD WINAPI Threadproc1(LPVOID p)
{
CThread2Dlg pDlg = (CThread2Dlg) p;
while(1)
{
EnterCriticalSection(&cs);

    if (nTiecks > 0)
    {

        CString str;
        str.Format("%d",nTiecks);
        pDlg->m_list1.AddString(str);
        nTiecks--;
        LeaveCriticalSection(&cs);
    }
    else
    {
        LeaveCriticalSection(&cs);
        break;
    }

}
return 0;

}
DWORD WINAPI Threadproc2(LPVOID p)
{
CThread2Dlg *pDlg = (CThread2Dlg *)p;
while(1)
{
EnterCriticalSection(&cs);

    if (nTiecks > 0)
    {
        CString str;
        str.Format("%d",nTiecks);
        pDlg->m_list2.AddString(str);
        nTiecks--;
        LeaveCriticalSection(&cs);
    }
    else
    {
        LeaveCriticalSection(&cs);
        break;
    }

}
return 0;

}
void CThread2Dlg::OnButton1()
{
// TODO: Add your control notification handler code here

nTiecks = 30;
m_list1.ResetContent();
m_list2.ResetContent(); 
    InitializeCriticalSection(&cs);

hthread1 = CreateThread(NULL,0,Threadproc1,this,0,NULL);
hthread2 = CreateThread(NULL,0,Threadproc2,this,0,NULL);
CloseHandle(hthread1);
CloseHandle(hthread2);

Sleep(1000);
::DeleteCriticalSection(&cs);

}

1个回答

zh852
zh852   2016.12.02 14:20

你跟踪下两个线程是否跑完了,别用sleep 用waitformultiobject,等两个线程退出了再deletecriticalsection

Csdn user default icon
上传中...
上传图片
插入图片