csdn已经解决(间隔180秒发)

本文介绍了一个使用C++实现的线程池示例,包括两个工作线程和一个定时器线程。通过创建事件、线程池工作项及定时器,实现了线程间的同步与定时触发任务的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// ThreadPool.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <conio.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include "stdafx.h"  
#define WIN32_LEAN_AND_MEAN  
#include <windows.h>  
#include <iostream>  
using namespace std;  
PTP_TIMER g_Timer;  
PTP_WORK work1, work2; //2个线程。  
void A();  
void B();  
void C();  
void D();  
volatile LONG iCount = 0;  
HANDLE hEvent = NULL;  // FINISH
HANDLE ha, hb, hc, hd;
CRITICAL_SECTION g_cs;
VOID NTAPI thread_x(PTP_CALLBACK_INSTANCE, PVOID, PTP_WORK)  
{  
	A(); 
	C();
}  
VOID NTAPI thread_y(PTP_CALLBACK_INSTANCE, PVOID, PTP_WORK)  
{  
	B();  
	D();  
}  

VOID NTAPI TimerHandler(PTP_CALLBACK_INSTANCE, PVOID, PTP_TIMER)  
{  
	//InterlockedIncrement(&iCount); 
	if (iCount < 10)  
	{   
		SetEvent(hd);
	}  
}  
void A()  
{  
	WaitForSingleObject(ha, INFINITE);
	ResetEvent(ha);
	EnterCriticalSection(&g_cs);
	cout << "命令A\n";  
	LeaveCriticalSection(&g_cs);

	SetEvent(hb);
}  
void C()  
{  
	WaitForSingleObject(hc, INFINITE);
	ResetEvent(hc);
	EnterCriticalSection(&g_cs);
	cout << "命令C\n";  
	LeaveCriticalSection(&g_cs);

	FILETIME ft;  
	ULARGE_INTEGER ulRelativeTime;
	ulRelativeTime.QuadPart = (LONGLONG)-3*10000000;
	ft.dwHighDateTime = ulRelativeTime.HighPart;
	ft.dwLowDateTime = ulRelativeTime.LowPart;
	SetThreadpoolTimer(g_Timer, &ft, 0, 0); //由这个来发信号
}  
void B()  
{  
	WaitForSingleObject(hb, INFINITE);
	ResetEvent(hb);
	EnterCriticalSection(&g_cs);
	cout << "命令B\n";
	LeaveCriticalSection(&g_cs);
	SetEvent(hc);
}  

void D()  
{  
	WaitForSingleObject(hd, INFINITE);
	ResetEvent(hd);
	EnterCriticalSection(&g_cs);
	cout << "命令D\n";
	cout << "第" << iCount << "计算\n";
	LeaveCriticalSection(&g_cs);

	if (++iCount < 10)
	{
		SubmitThreadpoolWork(work1);
		SubmitThreadpoolWork(work2);
		SetEvent(ha);
	}
	else
	{
		SetEvent(hEvent);
	}
}  
int _tmain(int argc, _TCHAR* argv[])  
{  
	InitializeCriticalSection(&g_cs);
	ha = CreateEvent(NULL, TRUE, FALSE, NULL);
	hb = CreateEvent(NULL, TRUE, FALSE, NULL);
	hc = CreateEvent(NULL, TRUE, FALSE, NULL);
	hd = CreateEvent(NULL, TRUE, FALSE, NULL);

	work1 = CreateThreadpoolWork(thread_x, NULL, NULL);  
	work2 = CreateThreadpoolWork(thread_y, NULL, NULL);  
	g_Timer = CreateThreadpoolTimer(&TimerHandler, 0, 0);  
	hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);  

	SubmitThreadpoolWork(work1);
	SubmitThreadpoolWork(work2);

	SetEvent(ha);
	WaitForSingleObject(hEvent, INFINITE);  
	DeleteCriticalSection(&g_cs);
	cout << "finished.\n";  
	return 0;  
}  

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值