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: https://github.com/gouravdhar/cpp-threads
First things first, the prerequisites include :
Basic Understanding of C++ language.
Functors in C++. Its a short read incase you are not aware (https://www.geeksforgeeks.org/functors-in-cpp/)
Lambda Expression in C++. Go through a few codes to get the hang of it. (https://www.geeksforgeeks.org/lambda-expression-in-c/)
The flow of the blog would be :
What are threads and why to use them?
First C++ Thread.
Multithreading in C++.
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().
