gpt4 book ai didi

c++ - Win32 线程生产者更新消费者线程

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:34:57 24 4
gpt4 key购买 nike

我正在尝试使用基于类的 Win32 线程实现来创建生产者线程和消费者线程。消费者中int x类型的信息由生产者更新。

Producer and Consumer both inherit from IRunnable
struct IRunnable {
virtual unsigned long run() = 0;
virtual void stop() = 0;
};

它为 Thread 类创建一个接口(interface),

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;
}

线程::运行是

unsigned long run() {
_started = true;
unsigned long threadExitCode = _runnable->run();
_started = false;
return threadExitCode;
}

当我运行代码时,出现未处理的异常。访问冲突写入位置 0X... 在行 this->consData->x = 1;

如有任何帮助,我们将不胜感激。

最佳答案

在第一个 try block 中,您将 Consumer 实例分配给新创建的局部变量 Consumer *obj1,而不是使用在 try block 之前创建的现有变量。尝试这样的事情:

Consumer *obj1=0;
Thread *consumerThread=0;

try {
// create the threadable object first
obj1 = new Consumer();

这会修改现有变量而不是创建新变量。 Producer *obj、Thread *consumerThread 和 Thread *ProducerThread 的情况相同。请阅读有关 C++ 中变量的作用域和生命周期的内容。

关于c++ - Win32 线程生产者更新消费者线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6262184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com