孙鑫 第十五/十六课之二 线程同步Semaphore

来源:互联网 发布:php二次开发 编辑:程序博客网 时间:2024/05/16 23:43

1 说明

信号量对象可以限制最多并发的线程个数,从而可以实现M个线程访问N个资源的目的(M>=N),包括最大信号量个数和初试信号量个数。

 

①创建信号量对象

CSemaphore( 

LONG    lInitialCount= 1,  //初试信号量个数

LONG    lMaxCount= 1,  //最大信号量个数

LPCTSTR    pstrName= NULL,  //名字

 LPSECURITY_ATTRIBUTES    lpsaAttributes= NULL //安全属性

);

eg.

const LONG INITNUM = 2;

const LONG MAXNUM = 2; 

CSemaphore  outputSemaphore(INITNUM, MAXNUM);

 

②等待信号量

WaitForSingleObject(outputSemaphore.m_hObject, INFINITE); //无限期等待请求信号量


③释放信号量

BOOL  ReleaseSemaphore(

HANDLE  hSemaphore, //信号量句柄,信号量对象的m_hObject成员

LONG  lReleaseCount, //释放的信号量个数

LPLONG  lpPreviousCount //之前信号量个数, 可为NULL

);

eg.

ReleaseSemaphore(outputSemaphore.m_hObject, 1, NULL);



2 实例

用三个线程来分别给三个编辑框赋值,但是只有两个信号量,总有一个线程在等待信号量


////////////////////////////////////////////72CSemaphoreDlg.h 类声明//////////////////////////

public:

    //线程函数

    static UINT MyThread1(LPVOID lpParam);

    static UINT MyThread2(LPVOID lpParam);

    static UINT MyThread3(LPVOID lpParam);


////////////////////////////////////////////72CSemaphoreDlg.cpp 类定义//////////////////////////

#include "afxmt.h" //信号量类头文件

#define INITNUM 2 //初始信号量个数

#define MAXNUM 2 //最大信号量个数

CSemaphore outputSemaphore(INITNUM, MAXNUM); //定义信号量对象

 

BOOL CMy72CSemaphoreDlg::OnInitDialog()

{

    //codes

    CWinThread* pThread1 = AfxBeginThread(MyThread1, (LPVOID)&m_ctrlEdit1);

    CWinThread* pThread2 = AfxBeginThread(MyThread2, (LPVOID)&m_ctrlEdit2);

    CWinThread* pThread3 = AfxBeginThread(MyThread3, (LPVOID)&m_ctrlEdit3);

    //codes

    return TRUE;  

}



//线程函数1

UINT CMy72CSemaphoreDlg::MyThread1(LPVOID lpParam)

{

    int a = 0;

    CEdit* pEdit = (CEdit*)lpParam;

    CString str;

    while (true)

    {

        WaitForSingleObject(outputSemaphore.m_hObject, INFINITE); //等待信号量

        str.Format("%d", ++a);

        pEdit->SetWindowText(str);

        Sleep(2000);

        ReleaseSemaphore(outputSemaphore, 1, NULL); //释放信号量

    }  

    return 0;

}

 


//线程函数2

UINT CMy72CSemaphoreDlg::MyThread2(LPVOID lpParam)

{

    int b = 0;

    CEdit* pEdit = (CEdit*)lpParam;

    CString str;

    while (true)

    {

        WaitForSingleObject(outputSemaphore.m_hObject, INFINITE); //等待信号量

        str.Format("%d", ++b);

        pEdit->SetWindowText(str);

        Sleep(2000);

        ReleaseSemaphore(outputSemaphore.m_hObject, 1, NULL); //释放信号量

    }

    return 0;

}

 


//线程函数3

UINT CMy72CSemaphoreDlg::MyThread3(LPVOID lpParam)

{

    int c = 0;

    CEdit* pEdit = (CEdit*)lpParam;

    CString str;

    while (true)

    {

        WaitForSingleObject(outputSemaphore.m_hObject, INFINITE); //等待信号量

        str.Format("%d", ++c);

        pEdit->SetWindowText(str);

        Sleep(2000);

        ReleaseSemaphore(outputSemaphore.m_hObject, 1, NULL); //释放信号量

    }

    return 0;

}


孙鑫 第十五/十六课之二 线程同步Semaphore - 大灰狼 - 大灰狼 的博客