top of page

C++ Threads for beginners

Hi guys and girls ;). Hope you are doing good. I am going to keep this blog short and crisp. To make the best use of this blog I would recommend you to make your own modifications in the example codes and run them on your machine.

You can fork my repo to access code used in this blog:

First things first, the prerequisites include :

  1. Basic Understanding of C++ language.

  2. Functors in C++. Its a short read incase you are not aware (

  3. Lambda Expression in C++. Go through a few codes to get the hang of it. (

The flow of the blog would be :

  1. What are threads and why to use them?

  2. First C++ Thread.

  3. Multithreading in C++.

  4. Resource Sharing and Locks.

What are threads and why to use them?

Wikipedia defines thread as “In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system.”

Apart from the main thread, you can create your own threads to execute multiple instructions concurrently to save time.

Point to note : All the threads share the same resources, so it is important to synchronize the use of resources efficiently. By resources I mean( the code section, data section, and OS resources (like open files and signals) ).

First C++ Thread

The thread class is defined in #include<thread>” header file.

Creating a thread is simple. We need to pass a function pointer or a callable object(functor or lambda expressions), which would contain the code to be executed by the thread, to the constructor of the thread object. Have a look at the code, I have used a function pointer.

Passing function pointer to thread

thread::join() function makes the (this->) thread wait for the thread to complete its execution. In this case the main thread waits for ‘t’ thread to complete its execution. If many concurrent tasks are going on, we can synchronize the workflow using join().

thread::detach() makes both the threads(the creator and createe) independent of each other, i.e. both the threads would execute independently. Suppose we don’t want to use join()(i.e. not wait for the completion of the thread we created because we don’t care anymore about its flow of execution), in that case we call thread::detach(). Once detach() has been called, we won’t be able to join(). It’s always better to check if a thread is joinable using thread::joinable() and then join(), else we get error.

Detached Thread

As can be seen, main function didn’t wait for the thread to complete its execution. Since both the threads(main and t) are running concurrently the order of execution changes with every run. More like the threads race for resources(in this case “cout”). Let’s see what happens if we comment detach().