c++ - 从 Boost 线程返回 Double

标签 c++ multithreading boost

您好,我有一个应该返回 double 值的 Boost 线程。该函数如下所示:

void analyser::findup(const double startwl, const double max, double &myret){
  this->data.begin();
  for(int i = (int)data.size() ; i >= 0;i--){
    if(this->data[i].lambda > startwl){
      if(this->data[i].db >= (max-30)) {
        myret = this->data[i+1].lambda;
        std::cout <<"in thread " << myret << std::endl;
        return;
      }
    }
  }
}

这个函数被另一个函数调用:

void analyser::start_find_up(const double startwl, const double max){
  double tmp = -42.0;
  boost::thread up(&analyser::findup,*this, startwl,max,tmp);
  std::cout << "before join " << tmp << std::endl;
  up.join();
  std::cout << "after join " << tmp << std::endl;
}

无论如何,我已经尝试并用谷歌搜索了几乎所有内容,但我无法让它返回一个值。

现在的输出看起来像这样。

before join -42
in thread 843.487
after join -42

感谢您的帮助。

最佳答案

tmp 在线程加入后没有获得预期值,因为创建 boost::thread 对象会将所有参数复制到线程存储 (see documentation)。

您必须用 boost::ref 封装 tmp,它具有提供“可复制构造的引用”的效果(抱歉,如果术语不合适,但这是想法)

double tmp = -42.0;
boost::thread up(&analyser::findup,*this, startwl,max, boost::ref(tmp));

更多关于 Thread Management documentation

关于c++ - 从 Boost 线程返回 Double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5156174/

相关文章:

c++ - std::move 和 unique_ptr::reset 之间有什么区别?

c++ - 在 _USE_32BIT_TIME_T 上使用 C++11 的计时

c++ - 如何从构造函数参数初始化模板成员数组?

c++ - cmake 命令找不到 boost 库

ubuntu - 如何在 Travis-CI 上使用 boost-build 构建?

c++ - 在另一个宏中使用一个宏,然后取消定义(#undef)第一个宏c++

c++ - 使用 OpenMP 并行化 c++ Monte Carlo Integration 的最佳方法是什么?

c - 线程在 WIC 中(有时)返回错误

java - 更改类加载器

c++ - 混合 C++ 和 Objective-C