Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

1. Objectives Understand the race condition Know the multithreading programming Understand how to use mutex to solve the race condition 2. Run the following code

1. Objectives

Understand the race condition

Know the multithreading programming

Understand how to use mutex to solve the race condition

2. Run the following code and explain what the code does

Run this code at least twice and take screenshots (20 points)

Explain what the code does (20 points)

What is the running result supposed to be (20 points)

What caused this issue? (10 points)

#include

#include

using namespace std;

const unsigned int NTHREADS = 20;

const int ITERS = 10000000;

int counter;

void increment()

{

for (int i = 0; i < ITERS; i++)

counter++;

}

void decrement()

{

for (int i = 0; i

counter--;

}

int main()

{

cout << "The counter is " << counter << endl;

thread *threads = new thread[NTHREADS];

or (unsigned int i = 0; i

if (i % 2 == 0)

threads[i] = thread(increment);

else

threads[i] = thread(decrement);

for (unsigned int i = 0; i

threads[i].join();

cout << "The counter is " << counter << endl;

return 0;

}

3. Mutex

A mutex (mutual exlusion) allows us to encapsulate blocks of code that should only be executed in one thread at a time.

Apply mutex to solve the issue in previous code. Show your revised code (20 points) and running result (10 points).

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Professional Microsoft SQL Server 2014 Administration

Authors: Adam Jorgensen, Bradley Ball

1st Edition

111885926X, 9781118859261

More Books

Students also viewed these Databases questions