Synchronizing the threads using mutex
As of now, we have successfully executed a multithreading code. However, a problem will occur if we consume a shared object and manipulate it inside the thread. It is called synchronization. In this section, we will try to avoid this problem by applying a mutex technique.
Avoiding synchronization issues
As we discussed earlier, in this section, we have to ensure that the shared object we run in the thread gives the correct value when it is executing. Let's suppose we have a global variable named counter and we plan to increase its value in all the five threads we have. Each thread will execute 10000 times increment iteration, so we expect to get 50000 as a result for all five threads. The code is as follows:
/* notsync.cpp */
#include <thread>
#include <iostream>
using namespace std;
auto main() -> int
{
cout << "[notsync.cpp]" << endl;
int counter = 0;
thread threads[5];
for...