1

Trying this with 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) I get this error on line //* of which I cannot find the reason:

error: expected primary-expression before ',' token

2) Is a reference parameter (r) a good way to get a value back from a thread? Or should I do like in Func2(), setting a member variable? (taking care of who wrote what)

3) Once I put a thread in a thread_group, how can I get values back from it? I cannot use the original pointer any more...

Thank you.

Pietro
  • 12,086
  • 26
  • 100
  • 193
  • 2
    You cannot. You should use a `packaged_task`; there's an example [in this long-winded answer](http://stackoverflow.com/a/12335206/596781). – Kerrek SB Jul 19 '13 at 18:18
  • 1
    You cannot use a bare member function name to get a pointer-to-member. You have to use `&MyClass::Func`. Both the class name and the ampersand are mandatory. – n. m. could be an AI Jul 19 '13 at 18:43

1 Answers1

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();
}
thomas
  • 505
  • 3
  • 12