Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ this as thread parameter, variables unavailable

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)
    }
}
like image 762
brecht Avatar asked Mar 26 '26 22:03

brecht


1 Answers

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...

like image 58
paquetp Avatar answered Mar 29 '26 11:03

paquetp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!