我想使用基于类的Win32线程实现来创建生产者线程和消费者线程。消费者中类型为int x的信息由生产者更新。Win32线程生产者更新消费者线程
Producer and Consumer both inherit from IRunnable
struct IRunnable {
virtual unsigned long run() = 0;
virtual void stop() = 0;
};
其中创建Thread类的接口,
class Thread {
public:
Thread(IRunnable *ptr=0) {
_runnable = ptr;
_started = false;
_threadHandle = 0;
}
一个线程类线程通过
DWORD threadID=0;
_threadHandle = ::CreateThread(0, 0, ThreadProc, this, 0, &threadID);
而且
static unsigned long __stdcall ThreadProc(void* ptr)
{
return ((Thread *)ptr)->run();
}
我如何使用它创建是
int _tmain(int argc, _TCHAR* argv[]) {
//example of usage
Consumer *obj1=0;
Thread *consumerThread=0;
try {
// create the threadable object first
Consumer *obj1 = new Consumer();
// create and start the thread the thread
Thread *consumerThread = new Thread(obj1);
consumerThread->start();
printf("OkCon.\n");
}
catch (ThreadException &e)
{
printf(e.Message.c_str());
}
Producer *obj=0;
Thread *ProducerThread=0;
try {
// create the threadable object first
Producer *obj = new Producer();
obj->Init(obj1);
// create and start the thread the thread
Thread *ProducerThread = new Thread(obj);
ProducerThread->start();
printf("OkProdu.\n");
}
catch (ThreadException &e)
{
printf(e.Message.c_str());
}
for(int i = 0; i<1000000; i++)
{int a = i;}// just lets the program run on a bit so the threads can run and do a bit more work
delete obj;
delete ProducerThread;
delete obj1;
delete consumerThread;
return 0;
}
消费run函数是
unsigned long Consumer::run()
{
while(_continue)
{
printf("readX, %d \n",x);
}
return 0;
}
初始化函数和生产经营的职能是
void Producer::Init(Consumer* aConsumer)
{
consData = aConsumer;
}
unsigned long Producer::run()
{
while(_continue)
{
this->consData->x = 1;
}
return 0;
}
主题::润
unsigned long run() {
_started = true;
unsigned long threadExitCode = _runnable->run();
_started = false;
return threadExitCode;
}
当我运行代码我得到一个未处理的异常。访问冲突写入位置0X ...在行this-> consData-> x = 1;
任何帮助将不胜感激。
你定义'cons'和'pro'两次,这表明这不是你真正的代码。 – sbi 2011-06-07 08:05:46
你的'Thread :: run()'函数做了什么? – Nick 2011-06-07 08:06:02
由于sbi说你没有向我们展示真实的代码。可能你只是在生产者初始化方法中传递NULL指针而不是指向Consumer的指针。 – Zuljin 2011-06-07 08:11:16