1

用 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)我在行//*上收到此错误,我找不到原因:

错误:“,”标记之前的预期主表达式

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

3) 一旦我将一个线程放入一个thread_group,我怎样才能从中取回值?我不能再使用原来的指针了...

谢谢你。

4

1 回答 1

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();
}
于 2013-07-20T11:10:10.200 回答