Windows api编程 多线程临界区卖票代码

编程还是得搞清楚操作系统的运行最重要,基础知识要打牢固。
#include <iostream>
#include <stdlib.h>
#include <Windows.h>




int ticke_number = 100;  //定义100张票。

CRITICAL_SECTION cs;  //定义全局临界区。


DWORD WINAPI ThreadFunc(LPVOID lpParameter) {
	char* name = (char*)lpParameter;
	while (true)
	{

		if (ticke_number <= 0) {
			printf("%s ============票卖完了==========\n", name);
			break;
		}

		EnterCriticalSection(&cs);
		if (ticke_number >0) {
			printf("%s 开始卖第 %d 张票了\n", name, ticke_number);
			ticke_number--;
		}
		LeaveCriticalSection(&cs);

		int x = rand() % 1000;
		Sleep(x);

	}
	return 0;
}


int main() {

	InitializeCriticalSection(&cs); //初始化临界区
	

   //A,B,C开始卖票。
   HANDLE threadHandle1 =  CreateThread(NULL, 0, ThreadFunc, (LPVOID)"A", 0, NULL);
   HANDLE threadHandle2 =  CreateThread(NULL, 0, ThreadFunc, (LPVOID)"B", 0, NULL);
   HANDLE threadHandle3 =  CreateThread(NULL, 0, ThreadFunc, (LPVOID)"C", 0, NULL);

   if (threadHandle1 == NULL || threadHandle2==NULL || threadHandle3==NULL) {
       perror("CreateThread error");
       return -1;
   }


   HANDLE lpHandles[] = {threadHandle1,threadHandle2,threadHandle3};


   WaitForMultipleObjects(3, lpHandles,TRUE,INFINITE); //等待所有的票卖完。


   DeleteCriticalSection(&cs); //删除临界区

   CloseHandle(threadHandle1);
   CloseHandle(threadHandle2);
   CloseHandle(threadHandle3);
   
   printf("主线程执行完毕");

   return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值