线程同步的3种实现方法 互斥对象 临界资源 事件对象
2015-05-22 13:37
309 查看
给懒的重新打代码的人用。
// Win32 Console.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <windows.h> #include <iostream> using namespace std; CRITICAL_SECTION g_cs; HANDLE g_hMutex; HANDLE g_hEvent; DWORD WINAPI ThreadProc1(LPVOID lpParam) { WaitForSingleObject(g_hEvent, INFINITE); // WaitForSingleObject(g_hMutex, INFINITE); // EnterCriticalSection(&g_cs); cout << "----1111111-------" << endl; // LeaveCriticalSection(&g_cs); // ReleaseMutex(g_hMutex); SetEvent(g_hEvent); return 0; } DWORD WINAPI ThreadProc2(LPVOID lpParam) { WaitForSingleObject(g_hEvent, INFINITE); // WaitForSingleObject(g_hMutex, INFINITE); // EnterCriticalSection(&g_cs); cout << "----2222222-------" << endl; // LeaveCriticalSection(&g_cs);LeaveCriticalSection(&g_cs); // ReleaseMutex(g_hMutex); SetEvent(g_hEvent); return 0; } int _tmain(int argc, _TCHAR* argv[]) { // InitializeCriticalSection(&g_cs); // g_hMutex = CreateMutex(NULL, TRUE, NULL); g_hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); DWORD idThread1 = -1; DWORD idThread2 = -1; DWORD param; HANDLE hThread1 = CreateThread(NULL, 0, ThreadProc1, (LPVOID)¶m, 0, &idThread1); CloseHandle(hThread1); HANDLE hThread2 = CreateThread(NULL, 0, ThreadProc2, (LPVOID)¶m, 0, &idThread2); CloseHandle(hThread2); // EnterCriticalSection(&g_cs); cout << "idThread1:" << idThread1 << endl; cout << "idThread2:" << idThread2 << endl; SetEvent(g_hEvent); // LeaveCriticalSection(&g_cs); // ReleaseMutex(g_hMutex); system("pause"); return 0; }
相关文章推荐
- 利用事件对象实现线程同步
- 线程同步的三种方法(互斥,事件,临界区) 之一 使用临界区对象
- 线程同步的三种方法(互斥,事件,临界区) 之二 使用互斥对象
- 线程同步的三种方法(互斥,事件,临界区) 之三 使用事件对象
- Java对象排序的3种实现方法
- 利用事件对象实现线程同步
- 利用事件对象实现线程同步
- 事件对象实现线程同步
- 事件对象实现线程同步
- 使用事件对象实现线程同步
- Java对象排序的3种实现方法
- 多线程编程Demo[利用事件对象实现线程同步]
- 多线程火车票售票系统——人工重置事件对象实现线程同步(会有问题的)
- 多线程火车票售票系统——自动重置事件对象实现线程同步
- [C++] socket - 5 [API事件对象实现线程同步]
- [C++] socket - 6 [API互斥事件对象实现线程同步]
- 用事件对象(Event)实现简单线程同步
- 利用事件对象实现线程同步
- 线程同步——内核对象实现线程同步——事件内核对象
- VC++多线程,互斥对象,事件对象,关键代码段实现线程同步