Portability
std::thread
is new to C++11 standard - with it, you can write portable code in C++ across compilers supporting C++11. You can feel the future
in it.
It is based on boost::thread
, which supports older compilers not supporting C++11 - which makes porting to other platforms even easier.
If you need to use platform specific tricks, std::thread::native_handle is the way to go.
CreateThread
is specific to WinAPI, this implies writing non-portable code. Also, this API is quite old and more inconvenient to use.
RAII
WinAPI is a C API which does not encourage modern C++ good practices. Every threading primitive you create, you must later destroy manually.
This is not the case for thread library in C++11, and this makes higher-level abstractions easier to write. While std::thread
is still fairly low-level (either you .join()
or .detach()
your thread, or the thread destructor will terminate your program), C++11 threading library has std::lock_guard
and other lock classes for supporting RAII for mutexes.
While C++11 has some higher-level abstractions, like std::async
for launching functions asynchronously, it does not provide other abstractions like threadpools, so you may want to use other libraries.
Type safety
WinAPI can only call function pointers with specific signature - which is prone to bugs related to type safety, lifetime of objects and mismanaging memory.
std::thread
can call any callable object:
// call free-standing function in a separate thread
std::thread first(func);
// call free-standing function with arguments (1, 2), in a separate thread
std::thread second(func, 1, 2);
// call static member function in a separate thread
std::thread third(&A::static_memfun);
// call non-static member of a temporary in a separate thread
std::thread fourth(&A::memfun, A());
//call std::function in a separate thread
std::function<void(int)> callback = std::bind(func, 1, _1);
std::thread fifth(callback, 2);
// call a function object
Functor f;
std::thread sixth(f);
TL;DR: There is no reason to use WinAPI threads as the main threading mechanism in new C++ code.