首页 > 代码库 > MFC信号量使用指南

MFC信号量使用指南

DEMO程序: TestSemaphore_DEMO.rar

源代码: TestSemaphore_SRC.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 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();
}


通过本教程可以迅速学会使用MFC中信号量的运用!

MFC信号量使用指南