Created
April 19, 2012 14:08
-
-
Save yohhoy/2421197 to your computer and use it in GitHub Desktop.
deferred thread start
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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