例1:模拟火车站的售票系统
模拟两个售票窗口共同卖100张票,因为要共享这100章票的资源
这时就要涉及到线程间的同步问题。
在下文中人为的添加了干预,当线程函数1运行到if判断语句后,挂起线程1,运行线程2,然后
线程2运行到if语句后,挂起线程2,接着回来运行线程1的显示。这样可以达到对全局变量访问的同步作用。
1 #include <Windows.h> 2 #include<iostream> 3 using namespace std; 4 DWORD WINAPI func1(LPVOID lparmaters); 5 DWORD WINAPI func2(LPVOID lparmaters); 6 7 int index=0; 8 int tickets=100; 9 10 DWORD WINAPI func1(LPVOID lparmaters) 11 { 12 /*while(index++<1000) 13 cout<<"thread1 is running"<<endl;*/ 14 while (1) 15 { 16 if(tickets>0) 17 { 18 Sleep(1); 19 cout<<"thread1 sell tickets:"<<tickets--<<endl; 20 } 21 else 22 break; 23 } 24 return 0; 25 } 26 27 DWORD WINAPI func2(LPVOID lparmaters) 28 { 29 while(1) 30 { 31 if(tickets>0) 32 { 33 Sleep(1); 34 cout<<"thread2 sell tickets:"<<tickets--<<endl; 35 } 36 else 37 break; 38 } 39 return 0; 40 } 41 int main() 42 { 43 44 HANDLE hthread1; 45 HANDLE hthread2; 46 hthread1=CreateThread(NULL,0,func1,NULL,0,NULL); 47 hthread2=CreateThread(NULL,0,func2,NULL,0,NULL); 48 CloseHandle(hthread1); 49 CloseHandle(hthread2); 50 Sleep(4000); 51 system("pause"); 52 }
时间: 2024-10-06 09:29:05