开发者

c++ : looking away to implement this scenario

I'm 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 (maybe function pointer) to generic thread factory/pool? in c++


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_;
};


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜