DEMO程序:TestSemaphore_DEMO.rar
---关键代码如下---
void CTestSemaphoreDlg::OnBnClickedButtonThread1()
{
// TODO: 在此添加控件通知处理程序代码
AfxBeginThread((AFX_THREADPROC)thread1WriteA, this);
} void CTestSemaphoreDlg::OnBnClickedButtonThread2()
{
// TODO: 在此添加控件通知处理程序代码
AfxBeginThread((AFX_THREADPROC)thread2WriteB, this);
} void CTestSemaphoreDlg::OnBnClickedButtonThread3()
{
// TODO: 在此添加控件通知处理程序代码
AfxBeginThread((AFX_THREADPROC)thread3WriteC, this);
} UINT CTestSemaphoreDlg::thread1WriteA( LPVOID pParam )
{
CTestSemaphoreDlg* pThis = (CTestSemaphoreDlg*)pParam;
pThis->WriteA();
return ;
} void CTestSemaphoreDlg::WriteA()
{
CString str;
g_semaphore.Lock();
for (int i=; i<; i++)
{
Sleep();
m_editDisp.GetWindowText(str);
str += "A";
m_editDisp.SetWindowText(str);
}
g_semaphore.Unlock();
} UINT CTestSemaphoreDlg::thread2WriteB( LPVOID pParam )
{
CTestSemaphoreDlg* pThis = (CTestSemaphoreDlg*)pParam;
pThis->WriteB();
return ;
} void CTestSemaphoreDlg::WriteB()
{
CString str;
g_semaphore.Lock();
for (int i=; i<; i++)
{
Sleep();
m_editDisp.GetWindowText(str);
str += "B";
m_editDisp.SetWindowText(str);
}
g_semaphore.Unlock();
} UINT CTestSemaphoreDlg::thread3WriteC( LPVOID pParam )
{
CTestSemaphoreDlg* pThis = (CTestSemaphoreDlg*)pParam;
pThis->WriteC();
return ;
} void CTestSemaphoreDlg::WriteC()
{
CString str;
g_semaphore.Lock();
for (int i=; i<; i++)
{
Sleep();
m_editDisp.GetWindowText(str);
str += "C";
m_editDisp.SetWindowText(str);
}
g_semaphore.Unlock();
}
通过本教程可以迅速学会使用MFC中信号量的运用!