windows编程点滴(四)之线程的同步

MSDN -- Synchronization Functions 

1. 使用临界区对象(CRITICAL_SECTION)

创建线程 unsigned long _beginthreadex(void *security , unsigned stack_size,

Unsigned(_stdcall *start_address)(void *),void *arglist, unsigned initflag,

Unsigned *thraaddr)

结束线程 void _endthreadex(unsigned retval);

初始化临界区 InitializeCriticalSection(LPCRITICAL_SECTION lpCriticalSection);

进入临界区 EnterCriticalSection( LPCRITICAL_SECTION lpCriticalSection);

离开临界区 void LeaveCriticalSection(LPCRITICAL_SECTION lpCriticalSection);

删除临界区 void DeleteCriticalSection(LPCRITICAL_SECTION lpCriticalSection);

#include <windows.h>

#include <stdio.h>

#include <process.h>

BOOL g_bContinue = TRUE;

int g_nCount1 = 0;

int g_nCount2 = 0;

CRITICAL_SECTION g_cs;

UINT WINAPI ThreadProc(LPVOID lpParam){

while (g_bContinue)

{

EnterCriticalSection(&g_cs);

g_nCount1++;

g_nCount2 ++;

LeaveCriticalSection(&g_cs);

}

return 0;

}

int main(int argc,char *argv[]){

UINT uId;

HANDLE hThreads[2];

//初始化临界区

InitializeCriticalSection(&g_cs);

hThreads[0] = (HANDLE)_beginthreadex(NULL,0,ThreadProc,NULL,0,&uId);

hThreads[1] = (HANDLE)_beginthreadex(NULL,0,ThreadProc,NULL,0,&uId);

Sleep(1000);

g_bContinue = FALSE;

WaitForMultipleObjects(2,hThreads,TRUE,INFINITE);

CloseHandle(hThreads[0]);

CloseHandle(hThreads[1]);

DeleteCriticalSection(&g_cs);

printf("g_nCount1=%d\tg_nCount2=%d\n",g_nCount1,g_nCount2);

return 0;

}

2. 互锁函数

InterlockedIncrement InterlockedDecrement InterlockedExchangAdd InterlockedExchangePointer

函数同步增一、减一

LONG InterlockedIncrement(LONG volatile *Addend);

LongInterlockedDecrement(LONG volatile *Addend);

你可能感兴趣的:(windows)