问题描述
- MFC多线程的挂起与启动问题
-
小弟在MFC多文档下编写的多线程编码,想运行OnThreadResume() 这个函数线程挂起,OnThreadSuspend()开始线程,但为什么调用了OnThreadResume()函数,在调用OnThreadSuspend() 会报错呢,线程的句柄是NULL呢?求解答啊
UINT CDrawView::DrawLine(LPVOID pParam)
{
PARAM m_pParam=(PARAM)pParam;
CBrush m_Brush;
CWnd m_Wnd;
CDC m_Dc;
//根据线程ID产生对应颜色的画刷
if(m_pParam->m_nID==0)
{
m_Brush.CreateSolidBrush(RGB(255,0,0));
}else if(m_pParam->m_nID==1){
m_Brush.CreateSolidBrush(RGB(0,255,0));
}else{
m_Brush.CreateSolidBrush(RGB(0,0,255));
}
//根据窗口句柄,得到CDC
m_Wnd.Attach(m_pParam->m_hWnd);
m_Dc=m_Wnd.GetDC();
CBrush *m_pOldBrush=(CBrush)m_Dc->SelectObject(&m_Brush);//重复画矩形,每次前进一个像素 for(int i=1;i<300;i++) { m_Dc->Rectangle(10,35+m_pParam->m_nID*50,10+i,55+m_pParam->m_nID*50); Sleep(100);//让线程暂停100ms,是为了可以明显的看到三个线程是同时执行的 } //(至少我的肉眼看来是这样的,实际并非如此) m_Dc->SelectObject(m_pOldBrush); m_Wnd.Detach(); return 0;
}
void CDrawView::OnThreadResume()
{
// TODO: Add your command handler code here
CString szContent = "确定要开启线程?";
PARAM *m_pParam[THREAD_NUM]={NULL,NULL,NULL};//传入线种入口函数的参数,初始化为空
CWinThread *m_pThread[THREAD_NUM];
for(int i=0;i<THREAD_NUM;i++){m_pThread[i]=NULL; m_pParam[i]=new PARAM; memset((void*)m_pParam[i],0,sizeof(PARAM));//将为入口函数参数分配 //的内存全部置0值 //写入线程ID和窗口句柄 m_pParam[i]->m_nID=i; m_pParam[i]->m_hWnd=GetSafeHwnd(); //启动线程 //if(IDYES == MessageBox(szContent,NULL,MB_YESNO)) m_pThread[i]=AfxBeginThread(DrawLine,(LPVOID)(m_pParam[i]),THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED); ASSERT(m_pThread[i]); m_pThread[i]->m_bAutoDelete = FALSE; //m_pThread[i]->ResumeThread(); //Sleep(10000); }
}
void CDrawView::OnThreadSuspend()
{
// TODO: Add your command handler code herefor (int i = 0; i < THREAD_NUM; i ++) { if (m_pThread[i] == NULL) { AfxMessageBox("错误"); } m_pThread[i]->ResumeThread(); }
}
解决方案
你在主线程中的挂起和恢复关你线程里的什么事情,根本不是一码事。
时间: 2024-10-10 10:37:57