views:

89

answers:

2

Hi im looking to find how to implement this scenario: i have logic code that is inside function, now i like to be able to execute this function in a separate thread. now what i have is a raw implementation of this .. i simple Init the Thread that in its Start/Run method i keep the function logic . how can i make it more generic ? so i could send the function ( mybe function pointer ) to generic thread factory/pool ? in c++

+3  A: 

This is the command pattern. The usual solution is to bundle the logic into a function object:

class DoSomething {
public:
    // Constructor accepts and stores parameters to be used
    // by the code itself.
    DoSomething(int i, std::string s)
        : i_(i), s_(s) { }

    void operator()() {
        // Do the work here, using i_ and s_
    }

 private:
    int i_;
    std::string s_;
};
Marcelo Cantos
A: 

Hi,

Have a look at boost::thread and boost::bind as these will become the std::tr1::thread and std::tr1::bind.

boost::thread is a small object, receiving a functor pointer with no return value and no arguments.

That means either a pointer to a function declared as void (*function)(void); or a struct/class implementing void operator()().

If you also use boost::bind, you can adapt basically any functor to be called as void (*functor)(void).

That's as flexible as you can get (as you can transform any function or function-like object to be called with no parameters, then launch it in it's own thread).

utnapistim