用户模式下线程同步之关键段
//注意其中的: InitializeCriticalSection是必须的,否则会报访问异常
// mycrical_section.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
const int count=10;
int g_nSum =0;
CRITICAL_SECTION g_cs;
DWORD WINAPI FirstThread(PVOID pvParam)
{
EnterCriticalSection(&g_cs);
g_nSum =0;
for(int n=1;n<=count;n++)
{
g_nSum +=n;
}
LeaveCriticalSection(&g_cs);
return g_nSum;
}
DWORD WINAPI SecondThread(PVOID pvParam)
{
EnterCriticalSection(&g_cs);
g_nSum =0;
for(int n=1;n<=count;n++)
{
g_nSum +=n;
}
LeaveCriticalSection(&g_cs);
return g_nSum;
}
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// TODO: Place code here.
DWORD dwThreadId1=0;
DWORD dwThreadId2=0;
InitializeCriticalSection(&g_cs); //初始化,不加会报访问异常
CreateThread(NULL,0UL,FirstThread,NULL,0,&dwThreadId1);
CreateThread(NULL,0UL,SecondThread,NULL,0,&dwThreadId2);
Sleep(50);
DeleteCriticalSection(&g_cs); //清理工作
return 0;
}