std::thread is the thread class that represents a single thread in C++.
To start a thread we simply need to create a new thread object and pass the executing code to be called (i.e, a callable object) into the constructor of the object.
Once the object is created a new thread is launched which will execute the code specified in callable.
A thread of execution is a sequence of instructions that can be executed concurrently with other such sequences in multithreading environments, while sharing a same address space.
An initialized thread object represents an active thread of execution; Such a object is called JOINABLE and has a unique thread id.
Few member functions are::
(constructor) Constructs thread (public member function )
(destructor) Thread destructor (public member function )
operator= Move-assign thread (public member function )
get_id Get thread id (public member function )
joinable Check if joinable (public member function )
join Join thread (public member function )
detach Detach thread (public member function )
swap Swap threads (public member function )
native_handle Get native handle (public member function )
hardware_concurrency [static] Detect hardware concurrency (public static member function )
Non-Member Functions::
swap(thread) Swap threads.
A Sample Program
// thread example
#include <iostream> // std::cout
#include <thread> // std::thread
void func1()
{
std::cout<<"Thread 1 executing"<<'\n';
}
void func2()
{
std::cout<<"Thread 2 executing"<<'\n';
}
int main()
{
std::thread first (func1); // spawn new thread that calls func1()
std::thread second (func2); // spawn new thread that calls func2()
std::cout << "main, func1 and func2 now execute concurrently...\n";
Comments