Question: Implementation : Implement the readers writers solution. Use main.cpp in the folder readersWriters as a start. Do not remove any code just add synchronization code
Implementation:
Implement the readers writers solution. 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.
readerswriter code:
#include
std::random_device e; std::uniform_int_distribution dist(1, 9); std::vector
//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 mythreads; 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 so
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
