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);
轉載于:https://www.cnblogs.com/cody1988/archive/2011/09/04/2166679.html
總結
以上是生活随笔為你收集整理的windows编程点滴(四)之线程的同步的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转载] 杜拉拉升职记——06 预算与排
- 下一篇: java信息管理系统总结_java实现科