#include <windows.h> #include <iostream> using namespace std; DWORD WINAPI MyThreadProc1(LPVOID lpParameter); //thread data DWORD WINAPI MyThreadProc2(LPVOID lpParameter); int tickets=100; CRITICAL_SECTION g_cs; int main(){ DWORD tid1=0,tid2=0; HANDLE handle1 = CreateThread(NULL,0,MyThreadProc1,NULL,CREATE_SUSPENDED ,&tid1); HANDLE handle2 = CreateThread(NULL,0,MyThreadProc2,NULL,CREATE_SUSPENDED ,&tid2); ResumeThread(handle1); ResumeThread(handle2); InitializeCriticalSection(&g_cs); Sleep(5000); DeleteCriticalSection(&g_cs); CloseHandle(handle1); CloseHandle(handle2); cout<< "SubThread1 ID:" << hex << uppercase<< tid1 << endl; cout<< "SubThread2 ID:" << hex << uppercase<< tid2 << endl; system("pause"); return 0; } DWORD WINAPI MyThreadProc1(LPVOID lpParameter ) { while(TRUE){ EnterCriticalSection(&g_cs); if(tickets){ cout<<"子线程1卖票:"<<tickets<<endl; --tickets; Sleep(15); LeaveCriticalSection(&g_cs); } else { LeaveCriticalSection(&g_cs); break; } } return 1; } DWORD WINAPI MyThreadProc2(LPVOID lpParameter) { while(TRUE){ EnterCriticalSection(&g_cs); if(tickets){ cout<<"子线程2卖票:"<<tickets<<endl; --tickets; Sleep(15); LeaveCriticalSection(&g_cs); } else { LeaveCriticalSection(&g_cs); break; } } return 1; }
CriticalSection关键代码区(临界区)
转载文章标签 CriticalSection 子线程 #include ios 文章分类 代码人生
-
【CAD建模号】学习笔记(二):工作区
工作区由[工具提示],[自适应网格],[自适应坐标轴],[参考坐标轴],[绘制的图形]组成。
自适应 坐标轴 工具提示 工作区 CAD建模号 -
临界区
程必须互斥地对它进行
临界区 临界资源 #include