nID == IDC_DSPYTHRDPRIORITY);
DWORD dw;
//取对应该ID的焦点选项
CComboBox* pBox = (CComboBox*) GetDlgItem(nID);
int nCurSel = pBox- >GetCurSel();
switch (nCurSel)
{
case 0:
dw = (DWORD)THREAD_PRIORITY_IDLE;break;
case 1:
dw = (DWORD)THREAD_PRIORITY_LOWEST;break;
case 2:
dw = (DWORD)THREAD_PRIORITY_BELOW_NORMAL;break;
case 3:
default:
dw = (DWORD)THREAD_PRIORITY_NORMAL;break;
case 4:
dw = (DWORD)THREAD_PRIORITY_ABOVE_NORMAL;break;
case 5:
dw = (DWORD)THREAD_PRIORITY_HIGHEST;break;
case 6:
dw = (DWORD)THREAD_PRIORITY_TIME_CRITICAL;break;
}
if (nID == IDC_CNTRTHRDPRIORITY)
m_pCounterThread- >SetThreadPriority(dw);
//调整计数线程优先级
else
m_pDisplayThread- >SetThreadPriority(dw);
//调整显示线程优先级
}
这样线程优先级的调整只需要根据不同的ID来调用该函数:
void CMutexesDlg::OnSelchangeDspythrdpriority()
{ OnPriorityChange(IDC_DSPYTHRDPRIORITY);}
void CMutexesDlg::OnSelchangeCntrthrdpriority()
{ OnPriorityChange(IDC_CNTRTHRDPRIORITY);}
复选线程挂起的实现代码如下:
void CMutexesDlg::OnPause()
{
//取挂起复选框状态
CButton* pCheck = (CButton*)GetDlgItem(IDC_PAUSE);
BOOL bPaused = ((pCheck- >GetState() & 0x003) != 0);
if (bPaused) {
m_pCounterThread- >SuspendThread();
m_pDisplayThread- >SuspendThread();
}//挂起线程
else {
m_pCounterThread- >ResumeThread();
m_pDisplayThread- >ResumeThread();
}//恢复线程运行
}
---- 程序在::OnClose() 中实现了线程的终止。在本例程当中对线程的终止稍微复杂些。需要注意的是成员变量m_bDone 的作用,在线程的运行当中循环检测该变量的状态,最终引起线程的退出。这样线程的终止是因为函数的退出而自然终止,而非采用强行终止的方法,这样有利于系统的安全。该程序中使用了PostMessage 函数,该函数发送消息后立即返回,这样可以避免阻塞。其实现的代码为:
void CMutexesDlg::OnClose()
{
int nCount = 0;
DWORD dwStatus;
//取挂起复选框状态
CButton* pCheck = (CButton*) GetDlgItem(IDC_PAUSE);
BOOL bPaused = ((pCheck- >GetState() & 0x003) != 0);
if (bPaused == TRUE){
pCheck- >SetCheck(0);//复选取消
m_pCounterThread- >ResumeThread();
//恢复线程运行
m_pDisplayThread- >ResumeThread();
}
if (m_pCounterThread != NULL){
VERIFY(::GetExitCodeThread(m_pCounterThread- >
m_hThread, &dwStatus));//取计数线程结束码
if (dwStatus == STILL_ACTIVE){
nCount++;
m_pCounterThread- >m_bDone = TRUE;
}//如果仍为运行状态,则终止
else{
delete m_pCounterThread;
m_pCounterThread = NULL;
}//如果已经终止,则删除该线程对象
}
if (m_pDisplayThread != NULL){
VERIFY(::GetExitCodeThread(m_pDisplayThread- >
m_hThread, &dwStatus));//取显示线程结束码
if (dwStatus == STILL_ACTIVE){
nCount++;
m_pDisplayThread- >m_bDone = TRUE;
}//如果仍为运行状态,则终止
else{
delete m_pDisplayThread;
m_pDisplayThread = NULL;
}//如果已经终止,则删除该线程对象
}
if (nCount == 0)//两个线程均终止,则关闭程序
CDialog::OnClose();
else //否则发送WM_CLOSE消息
PostMessage(WM_CLOSE, 0, 0);
}
---- 在例程具体实现中用到了许多函数,在这里不一一赘述,关于函数的具体意义和用法,可以查阅联机帮助。
……