【问题标题】:accessing member variable of boost thread object访问boost线程对象的成员变量
【发布时间】:2009-02-23 23:22:57
【问题描述】:

我正在使用一个对象来启动 boost 线程,它有一些我在线程中修改的公共成员变量(在 () 运算符中)。如何从线程外访问对象的成员变量?

我尝试使用在对象的 operator() 和外部都锁定的互斥锁(在对象的类中定义),但它似乎不起作用。

线程对象代码如下:

struct Mouse
{
  int x, y;
  string port;

  boost::mutex mutex;

  Mouse(const string& p) : port(p) { x = y = 0; }
  Mouse(const Mouse& m) : mutex() { x = m.x; y = m.y; port = m.port; }

  void operator()()  
  {
    ifstream ifs;
    ifs.open (port.c_str(), ios::binary );
    if (!ifs.is_open())
    {
      cout << "Impossible d'ouvrir " << port.c_str() << "\n";
      exit(0);
    }
    while (true) //modify x, y in infinit loop
      {
    char buf[3];
    ifs.read(buf, 3);
        unsigned char * msg = (unsigned char *) buf;
    unsigned char xsign = (msg[0]>>4) & 1;
    unsigned char ysign = (msg[0]>>5) & 1;
        unsigned char always1 = (msg[0]>>3) & 1;
    short dx = msg[1] - 256*xsign;
    short dy = msg[2] - 256*ysign;
    {
      boost::mutex::scoped_lock lock(mutex);
      x += abs(dx);
      y += dy;
    }
      }
  }
};

这是我尝试访问鼠标的 x 和 y 变量的地方:

  {
    boost::mutex::scoped_lock leftlock(leftMouse.mutex);
    xLeft = leftMouse.x;
    yLeft = leftMouse.y;
  }
  {
    boost::mutex::scoped_lock rightlock(rightMouse.mutex);
    xRight = rightMouse.x;
    yRight = rightMouse.y;
  }
  cout << xRight << " " << yRight << endl;  //this always prints 0 0

【问题讨论】:

  • 能否请您发布一些代码,看看它到底是如何不起作用的?

标签: c++ multithreading boost


【解决方案1】:

boost::thread 将传递的线程函数复制到内部存储,因此如果您这样启动线程,该线程将在mouse 的不同副本上运行:

int main() {
  Mouse mouse("abc.txt");
  boost::thread thr(mouse); // thr gets a copy of mouse
  ...
  // thread changes it's own copy of mouse
  ...
}

您可以使用boost::ref 来传递对现有对象的引用:

  Mouse mouse("abc.txt");
  boost::thread thr(boost::ref(mouse)); // thr gets a reference of mouse

在这种情况下thr 将修改全局mouse 对象,但您必须确保mousethr 完成之前不会超出范围或被销毁。

【讨论】:

    【解决方案2】:

    好的,现在我看得更清楚了。查看您的代码的一些建议:

    1. 不要公开内部互斥体。
    2. 写入锁定和解锁互斥锁的访问操作。这样,您就不必依靠您的班级用户来有效地锁定(和解锁)互斥锁。
    3. 在线程之前从文件中读取数据。可能读取是阻塞的,或者其他线程获取数据的速度太慢。如果之前读取数据,然后启动线程,客户端访问线程数据时,所有数据都会被读取。

    【讨论】:

      猜你喜欢
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 2011-06-01
      相关资源
      最近更新 更多