EnterCriticalSection 用法

#include
#include "afxmt.h"
using namespace std;

 
CRITICAL_SECTION cs;//可以理解为锁定一个资源
static int n_AddValue = 0;//定义一个静态的全部变量n_AddValue


DWORD WINAPI   FirstThread(LPVOID lParam)
{
    EnterCriticalSection(&cs);//加锁 接下来的代码处理过程中不允许其他线程进行操作,除非遇到LeaveCriticalSection
    for (int i = 0; i < 10; i++) {
        n_AddValue++;
        cout << "n_AddValue in FirstThread is " << n_AddValue << endl;
    }
    LeaveCriticalSection(&cs);//解锁 到EnterCriticalSection之间代码资源已经释放了,其他线程可以进行操作
    return 0;
}

DWORD WINAPI  SecondThread(LPVOID lParam)
{
    EnterCriticalSection(&cs);//加锁
    for (int i = 0; i < 10; i++) {
        n_AddValue++;
        cout << "n_AddValue in SecondThread is " << n_AddValue << endl;
    }
    LeaveCriticalSection(&cs);//解锁
    return 0;
}

int main()
{
    std::cout << "Hello World!\n";

    int nRetCode = 0;
 
    InitializeCriticalSection(&cs);//初始化结构CRITICAL_SECTION
    HANDLE   pFirstThread =  CreateThread(NULL, 0, FirstThread, NULL, 0, NULL);
    HANDLE   pSecondThread = CreateThread(NULL, 0, SecondThread, NULL, 0, NULL);
    HANDLE hThreadHandle[2];//
    hThreadHandle[0] = pFirstThread;
    hThreadHandle[1] = pSecondThread;
        //等待线程返回
    WaitForMultipleObjects(2, hThreadHandle, TRUE, INFINITE);
    DeleteCriticalSection(&cs);//删除临界区
    return nRetCode;
}

你可能感兴趣的:(c++)