views:

69

answers:

2

I have three classes:

class Rtss_Generator {
    int mv_transfersize;
}
class Rtss_GenSine : Rtss_Generator
class Rtss_GenSineRpm : Rtss_GenSine

Rtss_GenSine creates a thread in his constructer, it is started immediatly and the threadfunction is off-course declared static, waiting for an event to start calculating.

the problem: all the variables that are accessed through the gen-pointer are 0, but it does not fail. Also, this-address in the constructer and the gen-pointer-address in the thread are the same, so the pointer is ok.

this code is created and compile in visual studio 6.0 service pack 2003

ORIGINAL CODE

no thread

Rtss_GenSine::getNextData() {
    //[CALCULATION]
    //mv_transferSize is accessible and has ALWAYS value 1600 which is ok
} 

NEW CODE

Rtss_GenSine::Rtss_GenSine() {
   createThread(NULL, threadFunction, (LPVOID) this,0,0);
}

Rtss_GenSine::getNextData() {
     SetEvent(startCalculating);


     WaitForSingleObject(stoppedCalculaing, INFINITE);
} 

DWORD Rtss_GenSine::threadFunction(LPVOID pParam) {
    Rtss_GenSine* gen = (Rtss_GenSine*) pParam;

    while(runThread) {
        WaitForSingleObject(startCalculating, INFINITE);
        ResetEvent(startCalculating)

        //[CALCULATION]
        //gen->mv_transferSize ---> it does not fail, but is always zero
        //all variables accessed via the gen-pointer are 0

        setEvent(stoppedCalculaing)
    }
}
+2  A: 

Are you perhaps, doing something like this:

Rtss_GenSize someFunc()
{
   Rtss_GenSize temp;
   return temp;
}

Rtss_GenSine mygensize = some_func();

In this case, the constructor is called once, on a temporary instance, the copy constructor called to copy it to mygensize (twice), making 'this' no good to the thread that was spawned.

This could be the problem...the code that creates the instance of the Rtss_GenSine would help the investigation if you post it...

paquetp
this is not the case, the constructor is nicely called once with new. The original code works perfectly.
brecht
Just a shot in the dark - hard to guess without more code posted. Another guess below...
paquetp
It's solved now, i should not create a thread in the constructor, the this pointer is not fully initialized. The stupid problem is: the compiler does not complain about this, but it will always be unusable.
brecht
'this' is accessible in the constructor to access the members - perhaps it was a race condition, as detailed in my other answer? Eitherway, glad you solved your problem.
paquetp
A: 

Here's another guess - a race condition, the initialization of your startCalculating mutex to not be the owner, and mv_transferSize initialized after the constructor, but before the call to getNextData...

paquetp