views:

50

answers:

1

There are some member variables and mutexes associated with the object, so it would be easier to use a member function rather than a standalone function.

+2  A: 

Provide an operator() member func.

EDIT: like ...

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

struct MyThread
{
    int x;

    MyThread(): x( -1 ) {}
    void run()      // Name doesn't matter.
    {
        x = 42;
    }
};

int main()
{
    namespace b = boost;
    using namespace std;

    MyThread        t;
    b::thread_group g;

    g.create_thread( b::bind( &MyThread::run, &t ) ) ;
    // ... whatever
    g.join_all();
    cout << t.x << endl;    
}

Disclaimer: I'm unfamiliar with Boost threads. And this example added after answer was accepted.

Alf P. Steinbach
Can you elaborate? I don't understand your suggestion.
jonderry
A Boost thread doesn't take a function pointer, it takes a "callable". Which is any object that supports being called. As an off-the-cuff example, `struct Blah{ int operator() () { return 42; } }; int main() { Blah x; int y = x(); }`. The only problem is that a Boost thread may freely copy the object. So you might use some indirection. The easiest way to do some indirection is to construct a callable that refers to your object, like via `boost::bind`.
Alf P. Steinbach
Oh, ok, I just used boost::bind to pass the object as an argument to a a static member function. This seems kind of roundabout, but I guess it's the best I can do.
jonderry
@jonderry: OK, I added example code.
Alf P. Steinbach