绯路 2014-11-05 11:39 采纳率: 50%
浏览 2805

临界区 使用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 2016-12-02 06:20
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘