多线程和继承混乱 [英] Multi-threading and inheritance confusion

查看:71
本文介绍了多线程和继承混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


所有人都可能会告诉我我在做自己正在做的事情时遇到麻烦,但是任何帮助都将不胜感激.

所以我有这个基类:

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



从中,我得到另外两个类,即ClassA和ClassB.但是他们之间的关系是这样的:



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;
};



我使用静态变量是因为我在ClassA和ClassB中都使用了线程.

这个想法是ClassA运行一个单独的线程,该线程四处询问ClassB的线程是否正在运行.根据ClassB的线程是否正在运行,ClassA会执行不同的操作:



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



ClassB中的线程通过类似的方法处理:



The thread in ClassB goes around by a similar method:

void ClassB::MyThreadFunctionB()
{
  while(m_bMyBool)
  {
...
  }
}



我正在调试代码,发现如果您在ClassB中更改m_bMyBool,它也会在ClassA中对其进行更改.因此,如果要终止ClassB中的线程,则也要停止ClassA中的线程.但是,即使在ClassB中的线程停止后,ClassA中的线程也有其他事情要做.

尽管它们继承自相同的基类,但我认为它们不能像这样相互覆盖其成员变量.这是因为变量是静态的,还是因为ClassA中指向ClassB的指针变量是静态的?

请帮忙!
谢谢
P



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

推荐答案

应使用的变量应该在变量前使用volatile const来解决问题:-\
As One should use should use volatile const before the variable in order to get rid of the problem :-\


原因是因为bool变量是静态变量.
The reason is because the bool variable is a static variable.


这篇关于多线程和继承混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆