Problem with Multithreading (Critical Section Problem Part-1):

Goal: In this article, we will see what are the problems associated with multithreading.

We will take a function with name functionWithCriticalSection, and two threads t1, t2 will call this function.

Let’s see the code:

#include<iostream>
#include<thread>
using namespace std;

int x = 0;

void functionWithCriticalSection()
{
//this is the critical section
	x = 2;
	x = x+1;
}

int main()
{

	std::thread t1(functionWithCriticalSection);
	std::thread t2(functionWithCriticalSection);
	
	if(t1.joinable())
	{
		t1.join();
	}

	if(t2.joinable())
	{
		t2.join();
	}

	cout<<"Values of x:\t"<<x<<endl;

	return 0;

}

To Run the Code:

g++ -std=c++14 -pthread multithreadingProblem.cpp
./a.out

Output of the Code:

Values of x:	3
Values of x:	4

When we run the code multiple times, we see this strange output i.e. in one run we get x = 3, and in the another run we get 4. So we can say for the different runs, we are getting different outputs.

Note: When we you will the above code many times(can be upto 1000 times), then you will get x = 4.

So think about why the code is showing this strange behaviour?

This problem is called critical section problem.

So critical section is a block of code, where two/more threads/processes access the shared variables, and it ends up creating inconsistencies in the code output.


In our code, variable x is the shared variable, and line number 10, 11 is the critical section because this is the part of code where threads are accessing shared variable.

In the next post, we will see how we can deal with the ambiguous output.

Posted in C++