taz
taz

Reputation: 1526

Pass address of struct type to boost::thread?

Using Boost 1.43 threads, the following is compilable:

void MyClass::threadFn(...) { ... }
void MyClass::doFn(...) {
    ...
    boost::thread(&MyClass::threadFn, this, ...);
}

But the following is not compilable:

void MyClass:doFn(...) {
    ...
    struct MyStruct {
        MyStruct(...) { ... };
    }

    boost::thread(&MyStruct, ...);
}

This yields 'MyClass::doFn::MyStruct': illegal use of this type as an expression. Note that I am not trying to pass a pointer to an instance of MyStruct; I am trying to pass the type itself, as I would a function pointer, so that boost::thread will invoke the constructor of the type.

According to The Boost 1.43 Threads Spec:

A new thread is launched by passing an object of a callable type

So how do I pass the address of the struct type to the boost::thread function (AFAIK this would also apply to boost::bind)?

Further reading on how to accomplish this with functions

Upvotes: 1

Views: 438

Answers (3)

Max DeLiso
Max DeLiso

Reputation: 1244

MyStruct is not a callable type. You need to define a function which operates upon a MyStruct and then use that function to instantiate the thread instead.

A thread is an execution context, and to instantiate one you need a set of instructions for it to execute.

In Java, we see this in the form of a Runnable, which is used to instantiate a Thread, which can then be start()ed.

In C/C++ with Boost, you must use a function pointer.

The term "callable type" translates roughly into "type which is exchangeable with function pointer."

If you want to operate on an arbitrary struct, as in your example, MyStruct, you first must define a set of instructions ( a function ) which operates on that type.

Once you know the set of instructions, you can pass a pointer to that function to intantiate a thread, and then run that thread with arbitrary instances of MyStruct.

Code follows:

struct MyStruct {
        MyStruct(...) { ... }
    };

int frobnicateMyStruct( const MyStruct& msr ) {

    /* some operations on msr */

    return 0;
}    

void foo() {

    MyStruct myStructInstance;
    boost::thread(&frobnicateMyStruct, myStructInstance);

    /* ... */

    return;
}

Upvotes: 1

Jesse Good
Jesse Good

Reputation: 52365

I'm not really sure what the purpose is, but the following would call MyStruct():

boost::thread(boost::bind(boost::value_factory<MyStruct>()));

You can pass arguments also, for example with MyStruct(int i, int j):

boost::thread(boost::bind(boost::value_factory<MyStruct>(), 1, 2));

Upvotes: 1

Drew Dormann
Drew Dormann

Reputation: 63735

Instead of:

boost::thread(&MyStruct, ...);

Invoke an instance:

boost::thread(MyStruct(), ...);

Upvotes: 0

Related Questions