Advantages of thread join method in multithreading with an example

Advantages of thread join method in multithreading with an example

Advantages of thread join method in multithreading with an example. API Join() calling thread is suspended until the function called during construction completes. After all thread actions are complete and this procedure returns, this synchronises.

The thread object can be safely ended once this method has been called because it is no longer joinable.

Parameters


(none)

Return value


(none)

Postconditions


joinable() is false

Note:

  1. Once the thread is joined, get_id return 0.
  2. Default constructed thread get_id return 0.
#include <iostream>
#include <thread>
#include <chrono>


/// <summary>
/// Not accurate count of allowed thread
/// </summary>
void maximum_number_of_allowed_thread()
{
	std::cout << "Allowed max number of parallel threads : "
		<< std::thread::hardware_concurrency() << std::endl;
}


void thread_func()
{
	std::this_thread::sleep_for(std::chrono::milliseconds(1000));
	std::cout << "new  thread id : " << std::this_thread::get_id() << std::endl;
}


/// <summary>
/// 1. Once the thread is joined, get_id return 0.
/// 2. Default constructed thread get_id return 0. 
/// </summary>
void about_join()
{
	std::thread thread_1(thread_func);

	std::cout << "thread_1 id before joining : " << thread_1.get_id() << std::endl;
	thread_1.join();

	std::thread thread_2;

	std::cout << "default consturcted thread id : " << thread_2.get_id() << std::endl;
	std::cout << "thread_1 id after joining : " << thread_1.get_id() << std::endl;
	std::cout << "Main thread id : " << std::this_thread::get_id() << std::endl;
}

int main()
{
	maximum_number_of_allowed_thread();	 // example 1
	about_join();	 // example 2
}
////////////////// Output /////////////////////////// 
/*
Allowed max number of parallel threads : 8
thread_1 id before joining : 2964
new  thread id : 2964
default consturcted thread id : 0
thread_1 id after joining : 0
Main thread id : 22416 
*/