0
votes

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

The error I get is

/usr/include/boost/bind/bind.hpp: In instantiation of ‘void boost::_bi::list2::operator()(boost::_bi::type, F&, A&, int) [with F = void (Singleton::)(); A = boost::_bi::list0; A1 = boost::_bi::value; A2 = boost::_bi::value]’: /usr/include/boost/bind/bind_template.hpp:20:59: required from ‘boost::_bi::bind_t::result_type boost::_bi::bind_t::operator()() [with R = void; F = void (Singleton::)(); L = boost::_bi::list2, boost::_bi::value >; boost::_bi::bind_t::result_type = void]’ /usr/include/boost/thread/detail/thread.hpp:117:17: required from ‘void boost::detail::thread_data::run() [with F = boost::_bi::bind_t, boost::_bi::value > >]’ Singleton.cpp:4:1: required from here

I'm stuck and not sure what to do here, Thanks for your help.

1
Why are you giving run a NULL ? - user2249683
This is tagged C++11, so I'm curious as to why you aren't using those features in place of boost? - AndyG
Singleton():a(0){}, did you mean to write Singleton::Singleton():a(0){} or is that how it actually looks? - AndyG
Singleton::Singleton:a(0){} - Koten
Dieter Lücking You are correct, That solved it, but run doesn't have parameters? Isn't the third parameter of boost::thread with this signature is parameter passed to run? - Koten

1 Answers

0
votes

Given that your post is tagged C++11, I've taken the liberty of using its features. I've implemented your code without issue:

#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

Notice I use std::thread, defaulted constructor, a lambda, and an in-class member initializer.