Use std::thread for concurrency
A thread is a unit of concurrency. The main()
function may be thought of as the main thread of execution. Within the context of the operating system, the main thread runs concurrently with other threads owned by other processes.
The std::thread
class is the root of concurrency in the STL. All other concurrency features are built on the foundation of the thread
class.
In this recipe, we will examine the basics of std::thread
and how join()
and detach()
determine its execution context.
How to do it…
In this recipe, we create some std::thread
objects and experiment with their execution options.
- We start with a convenience function for sleeping a thread, in milliseconds:
void sleepms(const unsigned ms) { using std::chrono::milliseconds; std::this_thread::sleep_for(milliseconds(ms)); }
The sleep_for()
function takes a duration
object and blocks execution of the current thread...