#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;
}
windows多线程信号量1
最新推荐文章于 2024-10-10 09:50:01 发布
该代码示例展示了一个使用C++和WindowsAPI编写的多线程程序,通过信号量(Semaphore)来同步两个线程,模拟售票过程。当票数大于0时,线程可以销售一张票并更新票数;否则显示票已售罄。程序在主线程中创建两个售票线程,并在所有线程结束后关闭相关句柄。
摘要由CSDN通过智能技术生成