7/2/2018 - 8:46 PM

CPP : Thread initialization example

	Threads initialization 

#include <iostream>

// Functions and classes for managing threads are included in <thread>
#include <thread>

// The "initial function" of the thread
void hello()
	std::cout << "Hello Concurrent World 1!\n";

// The "callable" type object
class background_task
	void operator()()
		std::cout << "Hello Concurrent World 2!\n";

int main()
	std::thread t1(hello);

	// This is an example of "C++ most vexing parse", which interprets this as function declaration taking function pointer as argument
	// std::thread t2(background_task());

	// This is better declared using uniform initialization syntax. The object is copied into the thread so beware of dangling pointers.
	std::thread t2{ background_task() };

	// Thread can also be initialized using lambda expression
	std::thread t3([]()
		std::cout << "Hello Concurrent World 3!\n";

	// Wait for the additional threads to finish. Calling "join" on a thread object detaches the object from the thread, losing all information about that thread.
	// Failing to call "join" or "detach" will destroy the thread in the std::thread object destructor. "Detach" detaches the thread from the thread object.