如何从boost :: thread获取值?

时间:2013-07-19 18:13:36

标签: c++ multithreading boost boost-thread

尝试使用boost :: thread:

void MyClass::Func(int a, int b, int c, int &r) {
    r = a + b + c;
}

void MyClass::Func2(int a, int b, int c) {
    memberVar = a + b + c;
}

void MyClass::Work()
{
    int a = 1, b = 2, c = 3;
    int r;
    boost::thread_group tg;

    for(int i = 0; i < 10; ++j)
    {
        boost::thread *th = new boost::thread(Func, a, b, c, r);    //* error

        tg.add_thread(th);
    }

    tg.join_all();
}

1)我在行// *上得到了这个错误,我找不到原因:

  

错误:在','标记

之前预期的primary-expression

2)参考参数(r)是从线程中获取值的好方法吗?或者我应该在Func2()中设置成员变量? (照顾谁写了什么)

3)一旦我将一个线程放在thread_group中,我怎样才能从中获取值?我不能再使用原始指针......

谢谢。

1 个答案:

答案 0 :(得分:2)

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

using namespace std;

class MyClass{
public:
    void Func(int a, int b, int c, int &r) { r = a + b + c; }

    void Work()
    {
        using namespace boost;

        int a = 1, b = 2, c = 3;
        int r=0;

        thread_group tg;

        for(int i = 0; i < 10; ++i){
            thread *th = new thread(bind(&MyClass::Func,this,a, b, c, r));  
            tg.add_thread(th);

        }

        tg.join_all();
    }
};

void main(){
     MyClass a;
     a.Work();
}
相关问题