64,651
社区成员
发帖
与我相关
我的任务
分享
#pragma once
#include "windows.h"
#include "string"
using namespace std;
///抽象的线程基类
class AbstractThread
{
public:
AbstractThread(void);
virtual ~AbstractThread(void);
virtual void Run(void * para)=0;
DWORD Suspend();
DWORD Resume();
bool Stop();
bool IsAlive();
HANDLE GetHandle();
string GetThreadID();
string GetThreadName();
protected:
string threadName;
string threadID;
HANDLE threadHandle;
};
#pragma once
#include "..\MutexThreads\AbstractThread.h"
#include "windows.h"
typedef struct
{
int Number1;
int Number2;
} TPara;
class ProductThread:public AbstractThread
{
public:
virtual void Run(void * para);
ProductThread(void);
virtual ~ProductThread(void);
private:
static unsigned _stdcall ProductNumber(void * para);
static unsigned _stdcall WasteNumber(void * para);
static HANDLE ProduceHandle;
static HANDLE WasteHandle;
};
HANDLE ProductThread::ProduceHandle=NULL;
HANDLE ProductThread::WasteHandle=NULL;
ProductThread::ProductThread(void):AbstractThread()
{
srand((unsigned)time(NULL));
this->ProduceHandle=CreateSemaphore(NULL,1,1,NULL);
this->WasteHandle=CreateSemaphore(NULL,0,1,NULL);
this->threadName="";
}
void ProductThread::Run(void * para)
{
unsigned int a=0;
this->threadHandle=(HANDLE)_beginthreadex(NULL,0,ProductThread::ProductNumber,para,CREATE_SUSPENDED,&a);
char * temp=new char[255];
memset(temp,'\0',255);
_itoa(a,temp,10);
this->threadID.assign(temp);
delete[] temp;
}
unsigned _stdcall ProductThread::ProductNumber(void * para)
{
WaitForSingleObject(ProduceHandle,INFINITE);
TPara * p=(TPara *)para;
//等待生产的信号量,直到处于发信号状态,则生产数据
/*int num1=rand();
int num2=rand();*/
p->Number1=rand();
p->Number2=rand();
Sleep(rand()%1000);
ReleaseSemaphore(WasteHandle,1,NULL);
//随机产生两个数字,返回给主调函数
//并让消费信号量处于发信号状态
return 0;
}
unsigned _stdcall ProductThread::WasteNumber(void *para)
{
WaitForSingleObject(WasteHandle,INFINITE);
TPara *p=(TPara *) para;
long sum=p->Number1+p->Number2;
cout<<p->Number1<<"+"<<p->Number2<<"="<<sum<<endl;
ReleaseSemaphore(ProduceHandle,1,NULL);
return 0;
}
ProductThread::~ProductThread(void)
{
ReleaseSemaphore(this->ProduceHandle,1,NULL);
ReleaseSemaphore(this->WasteHandle,1,NULL);
CloseHandle(this->ProduceHandle);
CloseHandle(this->WasteHandle);
}