c++ - 访问boost线程对象的成员变量

标签 c++ multithreading boost

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

我尝试使用在对象的 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

最佳答案

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 对象,但您必须确保 mouse 不会超出范围或者在 thr 完成之前被销毁。

关于c++ - 访问boost线程对象的成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/579838/

相关文章:

c++ - 尝试将月份从整数转换为字符串

c++ - 当我以 "wb"模式写入文件时,会发生什么?

java - 登录多线程应用程序

multithreading - 共享库中的 block Go 例程

c++ - 如何使用 typedef unsigned 在 UML 中编写数据属性

c++ - SFML C++ 绘制到 RenderWindow 纯虚函数运行时失败

c# - 这是对 ThreadPool 的适当使用吗?我能确定它会为每个任务启动一个线程吗?

c++ - Visual Studio 在作者的 Boost Asio 示例中提示 co_await

c++ - 具有 Python GUI 和 C++ 后台模块的混合应用程序

logging - Boost 1.52.0 上的 Boost.Log 安装错误