Skip to content

Instantly share code, notes, and snippets.

@yohhoy
Created April 19, 2012 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yohhoy/2421197 to your computer and use it in GitHub Desktop.
Save yohhoy/2421197 to your computer and use it in GitHub Desktop.
deferred thread start
#include <iostream>
#define PROCESS (std::cout<<"do"<<std::endl)
//#define PROCESS (throw 42)
//--------------------------------
#ifdef TEST1
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
class X {
boost::shared_ptr<boost::thread> thread_;
void do_() { PROCESS; }
public:
~X()
{
if (thread_)
thread_->join();
}
void start()
{
thread_.reset(new boost::thread([this] { do_(); }));
}
};
#endif
//--------------------------------
#ifdef TEST2
#include <boost/thread.hpp>
class X {
boost::thread thread_;
void do_() { PROCESS; }
public:
~X()
{
if (thread_.joinable())
thread_.join();
}
void start()
{
boost::thread th([this] { do_(); });
thread_.swap(th);
}
};
#endif
//--------------------------------
#ifdef TEST3
#include <thread>
class X {
std::thread thread_;
void do_() { PROCESS; }
public:
~X()
{
if (thread_.joinable())
thread_.join();
}
void start()
{
thread_ = std::thread([this] { do_(); });
}
};
#endif
//--------------------------------
#ifdef TEST4
#include <boost/optional.hpp>
#include <boost/utility/in_place_factory.hpp>
#include <boost/thread.hpp>
class X {
boost::optional<boost::thread> thread_;
void do_() { PROCESS; }
public:
~X()
{
if (thread_)
thread_->join();
}
void start()
{
thread_ = boost::in_place([this] { do_(); });
}
};
#endif
//--------------------------------
#ifdef TEST5
#include <future>
class X
{
std::future<void> task_;
void do_() { PROCESS; }
public:
void start()
{
task_ = std::async(std::launch::async, [this]{ do_(); });
}
};
#endif
int main()
{
X x;
x.start();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment