In this blog we are going to learn thread programming using c++11 thread. In C++11 a new thread library is introduced. I think most of the c++ programmer know what is thread. Thread is called a light weight process. Both processes and threads are independent sequences of execution. The main difference is that threads in a process, run in a shared memory space, while processes run in separate memory spaces. A thread is an entity within a process and without a process thread is not possible.

How to create thread in C++11

#include <iostream>
#include <thread>

void foo() {
  std::cout << "hello thread \n";

int main() {
    // main process starts
    // create thread within main process for foo to run
    std::thread t(foo);
    // join main thread
    return 0;

How to compile

To compile above program run below command

g++ -std=c++11 sample.cpp -pthread -osample

How it works

  • At line number 11 , as soon as we create a thread object like std::thread t(foo) , a new thread within main process starts to run function foo.
  • The thread object t , in our program is taking function pointer foo as its argument. a function name without () is a function pointer.
  • At line number 13 ¬†t.join();¬† the thread is joining main thread. t.join() means the main process (thread) waits for child thread t to finish.
  • If you do not want main thread to wait for child thread t to finish , you can detached the thread just after creation of thread. see below example.

C++ 11 multithreading tutorial part 1

  • So after t.detach(), the thread t will run independently and the main thread will not wait for thread t to finish. So sometime you cannot see the output printed by function foo as shown in above animated gif image.

So far now we are familiar  about thread creation. In our above example we have created thread by passing function pointer into the thread object. There are other different ways to create threads.

Related Contents to follow