BOOST ::线程内会成员功能调用返回unique_lock Instantiation错误

boost::thread in-class member function call returns unique_lock instantiation error

本文关键字:unique lock Instantiation 错误 返回 功能 线程 成员 BOOST 调用      更新时间:2023-10-16

我正在使用 boost::thread从同一类的不同成员函数中调用课堂成员函数。我想主题的方法的声明是:

void ClassName::nnMetropolisStep(double random, std::vector<int> nums);

我正在通过以下方式从另一个成员函数创建线程:

boost::thread* tThread = new boost::thread(&ClassName::nnMetropolisStep,
                                           this,
                                           someRandom,someNums);

这些是我正在使用的代码中boost功能的唯一调用。

我在其他问题中看到,该语法将适用于非静态成员函数(并且我构造线程的方式没有访问问题)。但是,当我编译时,我会收到以下错误:

g++ -fPIC -std=c++11 -c -g -Wall `root-config --cflags --glibs` -MMD -c -o obj/IsingModel.o src/IsingModel.cpp
In file included from /usr/include/boost/thread/pthread/mutex.hpp:11:0,
             from /usr/include/boost/thread/mutex.hpp:16,
             from /usr/include/boost/thread/pthread/thread_data.hpp:12,
             from /usr/include/boost/thread/thread.hpp:17,
             from /usr/include/boost/thread.hpp:13,
             from src/interface/IsingModel.h:11,
             from src/IsingModel.cpp:11:
/usr/include/boost/thread/locks.hpp: In instantiation of 'boost::unique_lock<Mutex>& boost::unique_lock<Mutex>::operator=(boost::unique_lock<Mutex>&&) [with Mutex = boost::mutex]':
/usr/include/boost/thread/future.hpp:414:33:   required from here
/usr/include/boost/thread/locks.hpp:269:22: error: cannot bind  'boost::unique_lock<boost::mutex>' lvalue to 'boost::unique_lock<boost::mutex>&&'
         swap(temp);
                  ^
/usr/include/boost/thread/locks.hpp:279:14: note: initializing argument 1 of 'void boost::unique_lock<Mutex>::swap(boost::unique_lock<Mutex>&&) [with Mutex = boost::mutex]'
         void swap(unique_lock&& other)
          ^
make: *** [obj/IsingModel.o] Error 1

发生了什么事?显然,我要么在做不正确的事情,要么更糟糕的是,我的编译器设置存在问题。

我通过删除对boost的所有引用来找出答案,但#include语句除外。在我的标题文件中,我正在使用

#include "boost/thread.hpp"

有效,但不正确。一旦我将其更改为

#include "boost/thread/thread.hpp"

所有内容都没有抱怨。

我正在使用Boost的1.41.0版本。

您需要在线程对象创建期间使用boost::bind函数。例如:

    double rand = 0;
    std::vector<int> myVector;
    ClassName obj;
    auto threadObj = new        boost::thread(boost::bind(&ClassName::nnMetropolisStep,&obj,rand,myVector));