Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
You're all probably going to tell me I'm asking for trouble doing what I'm doing, but any help is greatly appreciated.

So I have this base class:
class MyBaseClass
{
...
  protected:
    static bool m_bMyBool;
...
};


From which, I get 2 other classes, ClassA and ClassB. But their relationship is like this:
class ClassA: public MyBaseClass
{
...
  private:
    static ClassB* m_pClassB;
};


I'm using static variables because I use threads in both ClassA and ClassB.

The idea is that ClassA runs a separate thread that goes around asking if ClassB's thread is running. ClassA does something different depending on whether ClassB's thread is running:

void ClassA::MyThreadFunctionA()
{
  while(m_bMyBool)
  {
    if(ClassBThreadRunning())
    {
      // do something
    }
    else
    {
      // do something else
    }
  }
}


The thread in ClassB goes around by a similar method:
void ClassB::MyThreadFunctionB()
{
  while(m_bMyBool)
  {
...
  }
}


I was debugging the code and found that if you change m_bMyBool in ClassB, it changes it in ClassA as well. So if I want to terminate the thread in ClassB, I consequently stop the thread in ClassA as well. But the thread in ClassA has other things to do even after the thread in ClassB stops.

Although they inherit from the same base class, I didn't think they could get their member variables over-written by each other like this. Is this because the variable is static, or because the pointer variable in ClassA pointing to ClassB is static?

Please help!
Thanks
P
Posted

As One should use should use volatile const before the variable in order to get rid of the problem :-\
 
Share this answer
 
The reason is because the bool variable is a static variable.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900