torm
torm

Reputation: 1536

Launch method in new thread

I have a vector with pointers of objects and I'm trying to launch object's method in a new thread (method have a parameter).

This is code, which I can't compile:

class CanaSynchDynamic {
...
    void start() (boost::barrier&);
...
};

and in main:

for(int i=0;i<pw;++i)
    vS1.push_back(new CanaSynchDynamic());

do {
        boost::barrier barrier(pw);
        boost::thread_group threads;
        for(int i=0;i<pw;++i)
            vS1[i]->more_steps(start,s[z]);
        for(int i=0;i<pw;++i)
            threads.create_thread(boost::bind(&CanaSynchDynamic::start,boost::ref(*(vS1[i])),boost::ref(barrier)));
        threads.join_all();

} while(something);

Error is:

    /usr/include/boost/thread/detail/thread.hpp: In instantiation of 'void
    boost::detail::thread_data<boost::reference_wrapper<T> >::run() [with F = CanaSynchDynamic]':
    simulation_3.cpp:278:1:   required from here
    /usr/include/boost/thread/detail/thread.hpp:98:17: error: no match for call to   '(CanaSynchDynamic) ()'

Do you have any idea?

Upvotes: 0

Views: 234

Answers (1)

Stephan Dollberg
Stephan Dollberg

Reputation: 34608

You can't use a reference_wrapper to pass the object from which the function shall be run. Instead you can just pass a pointer to your object:

threads.create_thread(boost::bind(&CanaSynchDynamic::start,vS1[i],boost::ref(barrier)));

Also, you might just store your objects in a vector and not pointers to them. If you need a pointer use a std::unique_ptr from C++11 or if that is not available maybe a boost::ptr_vector.

Upvotes: 2

Related Questions