我正在尝试使用基于类的Win32线程实现来创建Producer线程和Consumer线程。消费者中类型为int x的信息由生产者更新。
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;
}
消费者的运行功能是
unsigned long Consumer::run()
{
while(_continue)
{
printf("readX, %d \n",x);
}
return 0;
}
生产者的init函数和run函数是
void Producer::Init(Consumer* aConsumer)
{
consData = aConsumer;
}
unsigned long Producer::run()
{
while(_continue)
{
this->consData->x = 1;
}
return 0;
}
Thread :: Run是
unsigned long run() {
_started = true;
unsigned long threadExitCode = _runnable->run();
_started = false;
return threadExitCode;
}
当我运行代码时,我得到一个未处理的异常。访问冲突写入位置0X ...在此行 - > consData-&gt; x = 1;
非常感谢任何帮助。
答案 0 :(得分:1)
在第一个try块中,您将Consumer实例分配给新创建的局部变量Consumer * obj1,而不是使用在try块之前创建的现有变量。尝试这样的事情:
Consumer *obj1=0;
Thread *consumerThread=0;
try {
// create the threadable object first
obj1 = new Consumer();
修改现有变量而不是创建新变量。与Producer * obj,Thread * consumerThread和Thread * ProducerThread相同的故事。请阅读有关C ++中变量的范围和生命周期的内容。