Thead Library C++ Introduction














































Thead Library C++ Introduction



Introduction

  • 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.

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::
  1. (constructor)   Constructs thread (public member function )
  2. (destructor)     Thread destructor (public member function )
  3. operator=        Move-assign thread (public member function )
  4. get_id             Get thread id (public member function )
  5. joinable           Check if joinable (public member function )
  6. join                 Join thread (public member function )
  7. detach            Detach thread (public member function )
  8. swap              Swap threads (public member function )
  9. native_handle Get native handle (public member function )
  10. hardware_concurrency [static]   Detect hardware concurrency (public static member function )
Non-Member Functions::
  1. 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";

  // synchronize threads:
  first.join();                          // pauses until first finishes
  second.join();                     // pauses until second finishes

  std::cout << "func1 and func2 completed.\n"
  return 0;
}

OUTPUT



Comments