【问题标题】:How to put function inside a class into thread? (C++ using Boost)如何将类中的函数放入线程中? (使用 Boost 的 C++)
【发布时间】:2010-11-08 10:07:31
【问题描述】:

我有一个类,其中包含printf("hello main thread");printf("hello thread created inside class"); 等一些函数。每个理论上都可以使用类变量。如何将其中一个功能放入线程中? (使用 Boost 库的 C++)

【问题讨论】:

  • 我一头雾水,你说的理论上每个都可以使用类变量是什么意思?
  • @Space_C0wb0y:我猜他的意思是“方法”
  • 什么是将函数放入线程中?
  • @Space_C0wb0y:如果我不得不猜测,我会说这些(成员)函数不可能是static,因为它们使用非静态成员。

标签: c++ multithreading class function boost


【解决方案1】:

看看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"));

应该这样做。

但是,请注意 boost::thread 有一个已经执行此操作的构造函数:请参阅 this link

所以你基本上可以这样做:

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

【讨论】:

    【解决方案2】:

    您可以为此使用Boost.Bind

    class Foo {
    public:
        void someMethod(const std::string & text);
    };
    
    Foo foo;
    boost::thread(boost::bind(&Foo::someMethod, &foo, "Text"));
    

    【讨论】:

      【解决方案3】:
      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();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-29
        • 1970-01-01
        相关资源
        最近更新 更多