DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

std::thread c++11

std::thread

It is class in c++11, we can create a thread and start it just declaring an object of this class like any other object in c++. Example:

std::thread T1 (threadfunction, other argument if required)

There are two type of thread:

  1. Joinable (Main thread will wait for it using API join(T1.join())
  2. Detachable (Main thread will not wait for it, make it detachable using API T1.detach())

source code with example:

#include<iostream>
#include<thread>

void ThreadFunction(int a)
{
    std::cout<<"ThreadFunction:"<<a<<std::endl;
    std::this_thread::sleep_for(std::chrono::milliseconds(1000)*a);
    return ;
}


int main()
{
    std::cout<<"Simple Thread Functionalities"<<std::endl;

    //Thread 1 and its joinable
    std::thread t1(ThreadFunction, 5);
    std::cout<<"Thread started, thread id:"<<t1.get_id()<<std::endl;

    //Thread 2 and its detachable, main thread will NOT wait for it.
    std::thread t2(ThreadFunction, 2);
    std::cout<<"Thread started, thread id:"<<t2.get_id()<<std::endl;
    std::cout<<"Thread detaching, thread id:"<<t2.get_id()<<std::endl;
    t2.detach();

    //Thread 1 joinable so main thread is waiting for t1 to fininsh
    std::cout<<"Waiting for T1 to finish"<<std::endl;
    t1.join();

    return 0;
};

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer