windows多线程信号量1

该代码示例展示了一个使用C++和WindowsAPI编写的多线程程序,通过信号量(Semaphore)来同步两个线程,模拟售票过程。当票数大于0时,线程可以销售一张票并更新票数;否则显示票已售罄。程序在主线程中创建两个售票线程,并在所有线程结束后关闭相关句柄。
摘要由CSDN通过智能技术生成
#include <stdio.h>
#include <Windows.h>


using namespace std;

#define MAX_THREADS 1
#define BUFFER_SIZE 1



//定义一个共享变量
int ticketAmount = 2;
//定义一个信号量
HANDLE ghSemaphore;

//线程函数
DWORD WINAPI ticketAgent(void* arg) {
	DWORD dwWaitResult;
	//acquire semaphore
	dwWaitResult = WaitForSingleObject(
		ghSemaphore, //信号量句柄
		INFINITE);	//无限等待时间
	 

	int t = ticketAmount;
	if (t > 0) {
		printf("One ticket sold!\n");
		t--;
	}
	else
	{
		printf("Ticket sold out!\n");
	}
	ticketAmount = t;
	//release semaphore
	if (!ReleaseSemaphore(
		ghSemaphore,	//信号量句柄
		1,				//额外的计数,增加1
		NULL))			//不需要WaitTimeOut参数
	{
		printf("ReleaseSemaphore error:%d\n", GetLastError());
	}

	return TRUE;
}

int main(int argc, char const* argv[]) {
	//初始化一个新的信号量
	ghSemaphore = CreateSemaphore(
		NULL,			//默认安全属性
		BUFFER_SIZE,	//初始计数
		BUFFER_SIZE,	//最大计数
		NULL);			//无名称
	if (!ghSemaphore) {
		printf("CreateSemaphore failed: %d\n", GetLastError());
		return FALSE;
	}
	//创建两个线程
	HANDLE ticketAgent_tid[2];
	for (int i = 0; i < 2; i++) {
		ticketAgent_tid[i] = CreateThread(NULL, 0, ticketAgent, NULL, 0, NULL);
	}
	//等待两个线程结束
	for (int i = 0; i < 2; i++) {
		WaitForSingleObject(ticketAgent_tid[i], INFINITE);
	}
	//释放线程句柄
	for (int i = 0; i < 2; i++) {
		CloseHandle(ticketAgent_tid[i]);
	}


	printf("ticketAmount:%d", ticketAmount);

	//关闭信号量句柄
	CloseHandle(ghSemaphore);

	getchar();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值