Question
Part 1 Read the code in example1.cpp. It creates four threads: two to run the function doit and the other two to run a function
Part 1 Read the code in example1.cpp. It creates four threads: two to run the function doit and the other two to run a function object. The four threads run concurrently with two threads run doit() incrementing/decrementing the global variable _y_ and two threads run function objects incrementing/decrementing the local variable _x_. From the output you can see that there is data corruption since both _x_ and _y_ should be 0. To fix this problem uncomment the line with ``` #define SYNC ```. ### Question We learned that a mutex _m_ is locked with a wait(m), (in C++ it is ``` m.lock() ```) and unlocked with signal(m) (in C++ it is ``` m.unlock() ```). How is this done in example.cpp? What is a ``` lock_guard ``` ? Write your answer here by editing this file (no more that a few lines)
#### Answer
Write your answer here
example.cpp:
#include
//uncomment line below to get correct result //#define SYNC int y = 0; int num_iterations = 100000; int num_trials=10; std::mutex m; #define INC 1 #define DEC -1 int gcd(int a,int b) { if (b == 0) return a; return gcd(b, a % b); } void doit(int a, int b,int op) { for (int i = 0; i < num_iterations; i++) { gcd(a, b); #ifdef SYNC std::lock_guard
} } class funcObject { int& _x; int _a, _b, _op; public: funcObject(int& x, int a, int b,int op) :_x(x), _a(a), _b(b),_op(op) {} void operator() () { for (int i = 0; i
} };
int main() { int a, b; std::default_random_engine e; std::uniform_int_distribution } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started