int var; //全局变量 UINT ThreadFunction(LPVOIDpParam) { var = 0; while (var < MaxValue) { //线程处理 ::InterlockedIncrement(long*) &var); } return 0; } 请看下列程序: int globalFlag = false; DWORD WINAPI ThreadFunc(LPVOID n) { Sleep(2000); globalFlag = true; return 0; } int main() { HANDLE hThrd; DWORD threadId; hThrd = CreateThread(NULL, 0, ThreadFunc, NULL, 0, &threadId); if (hThrd) { printf("Thread launched/n"); CloseHandle(hThrd); } while (!globalFlag) ; printf("exit/n"); } |
HANDLE CreateEvent( LPSECURITY_ATTRIBUTES lpEventAttributes, // SECURITY _ATTRIBUTES结构指针,可为NULL BOOL bManualReset, // 手动/自动 // TRUE:在WaitForSingleObject后必须手动调用ResetEvent清除信号 // FALSE:在WaitForSingleObject后,系统自动清除事件信号 BOOL bInitialState, //初始状态 LPCTSTR lpName //事件的名称 ); |
HANDLE hEvent=OpenEvent(EVENT_ALL_ACCESS,true,"MyEvent"); ResetEvent(hEvent); |
临界区
定义临界区变量
CRITICAL_SECTION gCriticalSection; |
VOID WINAPI InitializeCriticalSection( LPCRITICAL_SECTION lpCriticalSection //指向程序员定义的CRITICAL_SECTION变量 ); |
VOID WINAPI DeleteCriticalSection( LPCRITICAL_SECTION lpCriticalSection //指向一个不再需要的CRITICAL_SECTION变量 ); |
VOID WINAPI EnterCriticalSection( LPCRITICAL_SECTION lpCriticalSection //指向一个你即将锁定的CRITICAL_SECTION变量 ); |
VOID WINAPI LeaveCriticalSection( LPCRITICAL_SECTION lpCriticalSection //指向一个你即将离开的CRITICAL_SECTION变量 ); |
void UpdateData() { EnterCriticalSection(&gCriticalSection); ...//do something LeaveCriticalSection(&gCriticalSection); } |
HANDLE CreateMutex( LPSECURITY_ATTRIBUTES lpMutexAttributes, // 安全属性结构指针,可为NULL BOOL bInitialOwner, //是否占有该互斥量,TRUE:占有,FALSE:不占有 LPCTSTR lpName //信号量的名称 ); |
HANDLE hMutex; hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, L"mutexName"); if (hMutex){ … } else{ … } |
BOOL WINAPI ReleaseMutex( HANDLE hMutex ); |
void UpdateResource() { WaitForSingleObject(hMutex,…); ...//do something ReleaseMutex(hMutex); } |
临界区
定义临界区变量
CRITICAL_SECTION gCriticalSection; |
VOID WINAPI InitializeCriticalSection( LPCRITICAL_SECTION lpCriticalSection //指向程序员定义的CRITICAL_SECTION变量 ); |
VOID WINAPI DeleteCriticalSection( LPCRITICAL_SECTION lpCriticalSection //指向一个不再需要的CRITICAL_SECTION变量 ); |
VOID WINAPI EnterCriticalSection( LPCRITICAL_SECTION lpCriticalSection //指向一个你即将锁定的CRITICAL_SECTION变量 ); |
VOID WINAPI LeaveCriticalSection( LPCRITICAL_SECTION lpCriticalSection //指向一个你即将离开的CRITICAL_SECTION变量 ); |
void UpdateData() { EnterCriticalSection(&gCriticalSection); ...//do something LeaveCriticalSection(&gCriticalSection); } |
HANDLE CreateMutex( LPSECURITY_ATTRIBUTES lpMutexAttributes, // 安全属性结构指针,可为NULL BOOL bInitialOwner, //是否占有该互斥量,TRUE:占有,FALSE:不占有 LPCTSTR lpName //信号量的名称 ); |
HANDLE hMutex; hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, L"mutexName"); if (hMutex){ … } else{ … } |
BOOL WINAPI ReleaseMutex( HANDLE hMutex ); |
void UpdateResource() { WaitForSingleObject(hMutex,…); ...//do something ReleaseMutex(hMutex); } |
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |