开发者

How to put function inside a class into thread? (C++ using Boost)

I have a class with some 开发者_如何学运维functions like printf("hello main thread"); and printf("hello thread created inside class");. Each can theoreticaly use class variables. How to put one of that functions into thread? (C++ using Boost libraries)


Take a look at boost::bind.

class Class
{
  public:
    void method(const char*);
};

// instance is an instance of Class
boost::thread(boost::bind(&Class::method, &instance, "hello main thread"));

Should do it.

However, note that boost::thread has a constructor that already does this: see this link.

So you can basically just do:

boost::thread(&Class::method, &instance, "hello main thread");


You can use Boost.Bind for that.

class Foo {
public:
    void someMethod(const std::string & text);
};

Foo foo;
boost::thread(boost::bind(&Foo::someMethod, &foo, "Text"));


typedef boost::shared_ptr<boost::thread> thread_ptr;

class your_class : boost::noncopyable  {
public:
    void run();
    void join();
    void signal_stop();

private:
    void your_thread_func();
    thread_ptr thread_;
};

void your_class::run()
{
    thread_ = thread_ptr(new boost::thread(boost::bind<void>(&your_class::your_thread_func, this))); 
}
void your_class::join()
{
    if (thread_) {
        thread_->join();
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜