如何对作为类方法的可调用函数进行线程化

时间:2012-10-08 11:07:29

标签: c++ boost c++11 visual-studio-2012 boost-thread

使用MS VC ++ 2012和Boost库1.51.0

这是我的问题的快照:

struct B {
    C* cPtr;
}

struct C {
    void callable (int);
}

void function (B* bPtr, int x) {
    // error [1] here
    boost::thread* thrPtr = new boost::thread(bPtr->cPtr->callable, x) 
    // error [2] here
    boost::thread* thrPtr = new boost::thread(&bPtr->cPtr->callable, x) 
}

[1]错误C3867:' C :: callable':函数调用缺少参数列表;使用'& C :: callable'创建指向成员的指针

[2]错误C2276:'&' :对绑定成员函数表达式的非法操作

1 个答案:

答案 0 :(得分:4)

你想要boost::thread* thrPtr = new boost::thread(&C::callable, bPtr->cPtr, x);。这是一个有效的例子:

#include <sstream>
#include <boost/thread.hpp>
#include <boost/bind.hpp>


struct C {
    void callable (int j)
    { std::cout << "j = " << j << ", this = " << this << std::endl; }
};

struct B {
    C* cPtr;
};

int main(void)
{
    int x = 42;
    B* bPtr = new B;
    bPtr->cPtr = new C;

    std::cout << "cPtr = " << bPtr->cPtr << std::endl;;

    boost::thread* thrPtr = new boost::thread(&C::callable, bPtr->cPtr, x);
    thrPtr->join();
    delete thrPtr;
}

示例输出:

cPtr = 0x1a100f0
j = 42, this = 0x1a100f0
相关问题