多线程的同一个功能使用哪个线程
Posted
技术标签:
【中文标题】多线程的同一个功能使用哪个线程【英文标题】:Which thread is used in the same function of multithread 【发布时间】:2017-12-27 06:22:11 【问题描述】:在 mfc 代码中,
声明如下
CWinThread* _pThread[5];
DWORD _ThreadArg[5] = HIGHEST_THREAD, // 0x00
ABOVE_AVE_THREAD, // 0x3F
NORMAL_THREAD, // 0x7F
BELOW_AVE_THREAD, // 0xBF
LOWEST_THREAD // 0xFF
;
int i;
for (i= 0; i< 5; i++)
_pThread[i] = AfxBeginThread(ThreadFunc,
&_ThreadArg[i],
THREAD_PRIORITY_NORMAL,
0,
//CREATE_SUSPENDED,
NULL,
NULL);
//_pThread[i]->ResumeThread();
// setup relative priority of threads
_pThread[0]->SetThreadPriority(THREAD_PRIORITY_HIGHEST);
_pThread[1]->SetThreadPriority(THREAD_PRIORITY_ABOVE_NORMAL);
_pThread[2]->SetThreadPriority(THREAD_PRIORITY_NORMAL);
_pThread[3]->SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
_pThread[4]->SetThreadPriority(THREAD_PRIORITY_LOWEST);
使用相同的线程函数
UINT CThreadPoolDlg::ThreadFuncTh1(LPVOID ThreadArg)
DWORD dwArg = *(DWORD*)ThreadArg;
//txtTh[0].SetWindowTextW(_T("23"));
AfxGetMainWnd()->GetDlgItem(IDC_THD1)->SetWindowText(_T("1"));
return 0;
如何检查同一函数中正在使用哪个线程?
【问题讨论】:
呃,每个线程都有自己的本地dwArg
,明确标识线程。您要解决的真正问题是什么?
此外,从拥有线程以外的线程更新窗口肯定会导致灾难。当您连 Windows GUI 编程的基础知识都无法理解时,您确定要使用 MFC 吗?
【参考方案1】:
我得到如下答案
_pThread[0] = AfxBeginThread(ThreadFunc,this,
THREAD_PRIORITY_NORMAL,
0,
NULL,
NULL);
_pThread[1] = AfxBeginThread(ThreadFunc,this,
THREAD_PRIORITY_NORMAL,
0,
CREATE_SUSPENDED,
NULL);
_pThread[2] = AfxBeginThread(ThreadFunc,this,
THREAD_PRIORITY_NORMAL,
0,
CREATE_SUSPENDED,
NULL);
线程函数声明如下
UINT CThreadPoolDlg::ThreadFunc(LPVOID ThreadArg)
CThreadPoolDlg* dwArg = (CThreadPoolDlg*)ThreadArg;
DWORD dThread = GetCurrentThreadId();
//txtTh[0].SetWindowTextW(_T("23"));
while(1)
CString strTemp;
if(dThread == dwArg->_pThread[0]->m_nThreadID)
AfxGetMainWnd()->GetDlgItem(IDC_THD1)->GetWindowText(strTemp);
int n = _wtoi(strTemp);
strTemp.Format(_T("%d"), ++n);
AfxGetMainWnd()->GetDlgItem(IDC_THD1)->SetWindowText(strTemp);
if(n > 5)
::SendMessage(dwArg->GetSafeHwnd(), OWM_MYMETHOD, 0, 0);
//dwArg->_pThread[1]->ResumeThread();
if(dThread == dwArg->_pThread[1]->m_nThreadID)
AfxGetMainWnd()->GetDlgItem(IDC_THD2)->GetWindowText(strTemp);
int n = _wtoi(strTemp);
strTemp.Format(_T("%d"), ++n);
AfxGetMainWnd()->GetDlgItem(IDC_THD2)->SetWindowText(strTemp);
if(n > 5)
dwArg->_pThread[2]->ResumeThread();
if(dThread == dwArg->_pThread[2]->m_nThreadID)
AfxGetMainWnd()->GetDlgItem(IDC_THD3)->GetWindowText(strTemp);
int n = _wtoi(strTemp);
strTemp.Format(_T("%d"), ++n);
AfxGetMainWnd()->GetDlgItem(IDC_THD3)->SetWindowText(strTemp);
Sleep(500);
return 0;
看看就知道了
DWORD dThread = GetCurrentThreadId();
dThread == dwArg->_pThread[1]->m_nThreadID
然后我会得到当前线程ID...
【讨论】:
以上是关于多线程的同一个功能使用哪个线程的主要内容,如果未能解决你的问题,请参考以下文章