管理自己的boost :: thread

时间:2015-12-17 21:03:24

标签: c++ boost singleton

Singleton.h

class Singleton{
public:
 static Singleton &getInstance() {
      static Singleton instance;
      return instance;
 }
 void start();
 void run();
 void join();

private:
 Singleton();
 int a;
 boost::thread thread;
};

Singleton.cpp

Singleton()::Singleton:a(0){}
void Singleton::run(){ a=1; }
void Singleton::start(){ thread = boost::thread(&Singleton::run, this, NULL); }
void Singleton::join(){ thread.join(); }

的main.cpp

Singleton::getInstance().start();
Singleton::getInstance().join();

我得到的错误是

  

/usr/include/boost/bind/bind.hpp:实例化'void   boost :: _ bi :: list2 :: operator()(boost :: _ bi :: type,F&,A&amp ;,,   int)[with F = void(Singleton :: )(); A = boost :: _ bi :: list0; A1 =   提高:: _双::值; A2 = boost :: _ bi :: value]':   /usr/include/boost/bind/bind_template.hpp:20:59:需要   'boost :: _ bi :: bind_t :: result_type boost :: _ bi :: bind_t :: operator()()[with R = void; F = void(Singleton :: )(); L =   boost :: _ bi :: list2,boost :: _ bi :: value&gt ;; boost :: _ bi :: bind_t :: result_type = void]'   /usr/include/boost/thread/detail/thread.hpp:117:17:需要   'void boost :: detail :: thread_data :: run()[with F =   boost :: _ bi :: bind_t,boost :: _ bi :: value> >]'Singleton.cpp:4:1:必需   从这里

我被困住了,不知道该怎么办, 谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

鉴于你的帖子被标记为 C ++ 11 ,我已经冒昧地使用它的功能。我已经毫无问题地实施了您的代码:

#include <thread>

class Singleton{
public:
   static Singleton &getInstance() 
   {
      static Singleton instance;
      return instance;
   }

   void start()
   {
      thread = std::thread(
         [this]() // lambda to call internal run method
         {
             run();
         });
   }

   void run()
   {
      a=1;
   }

   void join()
   {
      thread.join();
   }


private:
   Singleton() = default;
   int a = 0;
   std::thread thread;
};

Live Demo

注意我使用std::thread,默认构造函数,lambda和类内成员初始值设定项。