简体   繁体   中英

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM