Motivation: reason why I'm considering it is that my genius project manager thinks that boost is another dependency and that it is horrible because "you depend on it"(I tried explaining the quality of boost, then gave up after some time :( ). Smaller reason why I would like to do it is that I would like to learn c++11 features, because people will start writing code in it. So:
#include<thread> #include<mutex>
and
boost equivalents?P.S. I use GCC so headers are there.
There are several differences between Boost.Thread and the C++11 standard thread library:
std::async
, but Boost does notboost::shared_mutex
for multiple-reader/single-writer locking. The analogous std::shared_timed_mutex
is available only since C++14 (N3891), while std::shared_mutex
is available only since C++17 (N4508).boost::unique_future
vs std::future
)std::thread
are different to boost::thread
--- Boost uses boost::bind
, which requires copyable arguments. std::thread
allows move-only types such as std::unique_ptr
to be passed as arguments. Due to the use of boost::bind
, the semantics of placeholders such as _1
in nested bind expressions can be different too.join()
or detach()
then the boost::thread
destructor and assignment operator will call detach()
on the thread object being destroyed/assigned to. With a C++11 std::thread
object, this will result in a call to std::terminate()
and abort the application.To clarify the point about move-only parameters, the following is valid C++11, and transfers the ownership of the int
from the temporary std::unique_ptr
to the parameter of f1
when the new thread is started. However, if you use boost::thread
then it won't work, as it uses boost::bind
internally, and std::unique_ptr
cannot be copied. There is also a bug in the C++11 thread library provided with GCC that prevents this working, as it uses std::bind
in the implementation there too.
void f1(std::unique_ptr<int>);
std::thread t1(f1,std::unique_ptr<int>(new int(42)));
If you are using Boost then you can probably switch to C++11 threads relatively painlessly if your compiler supports it (e.g. recent versions of GCC on linux have a mostly-complete implementation of the C++11 thread library available in -std=c++0x
mode).
If your compiler doesn't support C++11 threads then you may be able to get a third-party implementation such as Just::Thread, but this is still a dependency.