【问题标题】:How can I get a value back from a boost::thread?如何从 boost::thread 中获取值?
【发布时间】:2013-07-19 03:16:50
【问题描述】:

用 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) 一旦我将一个线程放入一个线程组中,我怎样才能从中取回值?我不能再使用原来的指针了……

谢谢。

【问题讨论】:

  • 你不能。你应该使用packaged_task;有一个例子in this long-winded answer
  • 您不能使用裸成员函数名称来获取指向成员的指针。你必须使用&amp;MyClass::Func。类名和 & 符号都是必需的。

标签: c++ multithreading boost boost-thread


【解决方案1】:
#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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    相关资源
    最近更新 更多