互斥訊號量
---關鍵程式碼如下---
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 0;
}
void CTestSemaphoreDlg::WriteA()
{
CString str;
g_semaphore.Lock();
for (int i=0; i<5; i++)
{
Sleep(500);
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 0;
}
void CTestSemaphoreDlg::WriteB()
{
CString str;
g_semaphore.Lock();
for (int i=0; i<5; i++)
{
Sleep(500);
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 0;
}
void CTestSemaphoreDlg::WriteC()
{
CString str;
g_semaphore.Lock();
for (int i=0; i<5; i++)
{
Sleep(500);
m_editDisp.GetWindowText(str);
str += "C";
m_editDisp.SetWindowText(str);
}
g_semaphore.Unlock();
}