I am trying to use a class based implementation of Win32 threads to create a Producer thread and a Consumer thread. Information of type int x in the consumer is updated by the producer.
Producer and Consumer both inherit from IRunnable
struct IRunnable {
virtual unsigned long run() = 0;
virtual void stop() = 0;
};
Which creates an interface for class Thread,
class Thread {
public:
Thread(IRunnable *ptr=0) {
_runnable = ptr;
_started = false;
_threadHandle = 0;
}
a thread is created in class thread by
DWORD threadID=0;
_threadHandle = ::CreateThread(0, 0, ThreadProc, this, 0, &threadID);
And
static unsigned long __stdcall ThreadProc(void* ptr)
{
return ((Thread *)ptr)->run();
}
How I have used it is
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;
}
The run function for consumer is
unsigned long Consumer::run()
{
while(_continue)
{
printf("readX, %d \n",x);
}
return 0;
}
The init function and run function for producer are
void Producer::Init(Consumer* aConsumer)
{
consData = aConsumer;
}
unsigned long Producer::run()
{
while(_continue)
{
this->consData->x = 1;
}
return 0;
}
Thread::Run is
unsigned long run() {
_started = true;
unsigned long threadExitCode = _runnable->run();
_started = false;
return threadExitCode;
}
When I run the code I get an Unhandled exception. Access violation writing location 0X… at line this->consData->x = 1;
Any help would be greatly appreciated.
In first try block you are assigning Consumer instance to newly created local variable Consumer *obj1 instead of using existing variable that was created just before try block. Try something like this instead:
This modify existing variable instead of creating new one. Same story with Producer *obj, Thread *consumerThread and Thread *ProducerThread. Please read something about scope and lifetime of variables in C++.