Thursday, 25 June 2020

Multithreading: 3.Mutex

When we execute the below code. The output would appear random. We are trying to print 1 to 9 from main and 10 to 19 from the thread.

#include<thread>
#include<iostream>
using namespace std;
void print()
{
//printing frm thread
for (int i = 10; i < 20; i++)
{
cout <<"thread"<< i << endl;
}
}
void main()
{
thread t(print);//creating a thread instance
for (int i = 1; i <10; i++)
{
cout << "Main" << i << endl;
}
if (t.joinable()) //check if the thread is joinable
t.join();//main thread waits till child thread completes the task
cout << "main thread exiting" << endl;
}
view raw datarace.cpp hosted with ❤ by GitHub
The output looks like below

threadMain101
threadMain112
threadMain123
threadMain134
threadMain145
threadMain156
threadMain167
threadMain178
threadMain189
thread19

The output looks haphazard and not understandable. This is because both the main thread and the thread t are fighting for the common resource cout. We have to make a change in our code to control the access of cout. meaning if one thread is accessing cout, other thread has to simply wait for access.
We use std::mutex lock and unlock methods to do that.

void customcout(std::string&str, int i)
{
mut.lock();//locks access
cout << str << i << endl;
mut.unlock();//releases access
}
void print()
{
//printing frm thread
for (int i = 10; i < 20; i++)
{
customcout(string("thread:"), i);
}
}
void main()
{
thread t(print);//creating a thread instance
for (int i = 1; i <10; i++)
{
customcout(string("Main:"), i);
}
if (t.joinable()) //check if the thread is joinable
t.join();//main thread waits till child thread completes the task
cout << "main thread exiting" << endl;
}
view raw mutex.cpp hosted with ❤ by GitHub
below is the output after using mutex

thread:10
thread:11
thread:12
thread:13
thread:14
thread:15
thread:16
thread:17
thread:18
thread:19
Main:1
Main:2
Main:3
Main:4
Main:5
Main:6
Main:7
Main:8
Main:9

No comments:

Post a Comment