Note that there are some explanatory texts on larger screens.

plurals
  1. POWin32 threads producer updating a consumer thread
    text
    copied!<p>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.</p> <pre><code>Producer and Consumer both inherit from IRunnable struct IRunnable { virtual unsigned long run() = 0; virtual void stop() = 0; }; </code></pre> <p>Which creates an interface for class Thread, </p> <pre><code>class Thread { public: Thread(IRunnable *ptr=0) { _runnable = ptr; _started = false; _threadHandle = 0; } </code></pre> <p>a thread is created in class thread by</p> <pre><code>DWORD threadID=0; _threadHandle = ::CreateThread(0, 0, ThreadProc, this, 0, &amp;threadID); </code></pre> <p>And </p> <pre><code>static unsigned long __stdcall ThreadProc(void* ptr) { return ((Thread *)ptr)-&gt;run(); } </code></pre> <p>How I have used it is</p> <pre><code> 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-&gt;start(); printf("OkCon.\n"); } catch (ThreadException &amp;e) { printf(e.Message.c_str()); } Producer *obj=0; Thread *ProducerThread=0; try { // create the threadable object first Producer *obj = new Producer(); obj-&gt;Init(obj1); // create and start the thread the thread Thread *ProducerThread = new Thread(obj); ProducerThread-&gt;start(); printf("OkProdu.\n"); } catch (ThreadException &amp;e) { printf(e.Message.c_str()); } for(int i = 0; i&lt;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; } </code></pre> <p>The run function for consumer is</p> <pre><code>unsigned long Consumer::run() { while(_continue) { printf("readX, %d \n",x); } return 0; } </code></pre> <p>The init function and run function for producer are </p> <pre><code>void Producer::Init(Consumer* aConsumer) { consData = aConsumer; } unsigned long Producer::run() { while(_continue) { this-&gt;consData-&gt;x = 1; } return 0; } </code></pre> <p>Thread::Run is</p> <pre><code>unsigned long run() { _started = true; unsigned long threadExitCode = _runnable-&gt;run(); _started = false; return threadExitCode; } </code></pre> <p>When I run the code I get an Unhandled exception. Access violation writing location 0X... at line this->consData->x = 1;</p> <p>Any help would be greatly appreciated.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload