线程同步:CriticalSection关键区域
2009-05-28 11:40
288 查看
#include <Windows.h> #include <iostream> using namespace std; DWORD WINAPI Func1Proc( LPVOID lpParameter ); DWORD WINAPI Func2Proc( LPVOID lpParameter ); int tickets = 100; CRITICAL_SECTION g_cs; int main() { HANDLE hThread1; HANDLE hThread2; hThread1 = CreateThread(NULL, 0, Func1Proc, NULL, 0, NULL); hThread2 = CreateThread(NULL, 0, Func2Proc, NULL, 0, NULL); CloseHandle(hThread1); CloseHandle(hThread2); InitializeCriticalSection(&g_cs); Sleep(2000); DeleteCriticalSection(&g_cs); return 0; } DWORD WINAPI Func1Proc( LPVOID lpParameter ) { while(TRUE) { EnterCriticalSection(&g_cs); if (tickets > 0) { Sleep(10); cout << "thread1 sell ticket : " << tickets-- << endl; } else break; LeaveCriticalSection(&g_cs); } return 0; } DWORD WINAPI Func2Proc( LPVOID lpParameter ) { while(TRUE) { EnterCriticalSection(&g_cs); if (tickets > 0) { Sleep(10); cout << "thread2 sell ticket : " << tickets-- << endl; } else break; LeaveCriticalSection(&g_cs); } return 0; }
相关文章推荐
- linux线程同步之互斥锁——linux的关键区域
- window下线程同步之(Critical Sections(关键代码段、关键区域、临界区域)
- linux线程同步之互斥锁——linux的关键区域
- window下线程同步之(Critical Sections(关键代码段、关键区域、临界区域)
- VC++深入详解——第16章:线程同步,关键代码段
- CriticalSection关键代码区(临界区)
- 多线程编程Demo[关键代码段[临界区]实现线程同步]
- 线程同步--关键代码段
- STL线程同步最常用和最快速的临界段----CriticalSection
- Critical Section(关键区域,临界区域)
- 关键代码区 线程同步
- windows多线程系列004_利用关键代码段实现线程同步
- HDU 1426 Sudoku Killer(数独,划分区域是关键)
- 孙鑫 第十五/十六课之四 线程同步CriticalSection
- 互斥对象(Mutex)、事件对象(Event) 与 关键代码段(CriticalSection) 的比较(互斥量Mutex 保证只有一个实例运行)
- 秒杀多线程第五篇 经典线程同步 关键段(临界区,CriticalSection)
- C++使用CriticalSection实现线程同步
- 使用关键代码段实现线程同步
- 利用关键代码段实现线程同步
- CMM关键过程区域和四种用法