Question
this is the third time i post this question, please answer the question and add to this code. the other answers( that i got on
this is the third time i post this question, please answer the question and add to this code.
the other answers( that i got on chegg) is not correct since it holds a different code. thank you!
### Implementation
Implement the readers writers solution we discussed in class. Use **main.cpp** in the folder __readersWriters__ as a start. Do not **remove** any code just **add** synchronization code to fix the access problem. As you might have guessed you need to use ``` std::shared_mutex ``` here.
readerswriters.cpp:
// readersWriters.cpp : This file contains the 'main' function. Program execution begins and ends there. //
#include #include #include #include #include #include #include
std::random_device e; std::uniform_int_distribution dist(1, 9); std::vector v;
//Size of the vector v constexpr auto DATA_SIZE = 100; constexpr auto NUM_TRIALS = 10;
/* Readers writer setup. The common data is the * vector of integers v. The writers write a random * value from 1 to 9 followed by its negative such * that the total sum is 0. for example * [2,-2,2,-2,2,-2....] * The readers check that the sum in the vector is zero * if not it will print the sum (which means data is corrupted) */
/* You MUST NOT remove any of the code below. ADD to it sync * primites so that it works. Basically using c++ to implement the * solution we saw in class (it is in the lecture notes) */
class Reader { public:
void operator() () { int sum = 0;
for (auto x : v) { sum += x; std::this_thread::sleep_for(std::chrono::milliseconds(10)); }
if (sum != 0) std::cout
class Writer {
public: Writer() { } void operator() () { int value = dist(e);
for (auto& x : v) { x = value; value = -value; std::this_thread::sleep_for(std::chrono::milliseconds(10)); }
} };
int main() { int value = 1; for (int i = 0; i
} image: answer hint
Answer The shared_mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads. In contrast to other mutex types which facilitate exclusive access, a shared_mutex has two levels of access: shared - several threads can share ownership of the same mutex. exclusive - only one thread can own the mutex. Shared mutexes are usually used in situations when multiple readers can access the same resource at the same time without causing data races, but only one writer can do soStep 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