Skip to content

Instantly share code, notes, and snippets.

@stansidel
Created October 9, 2019 10:47
Show Gist options
  • Save stansidel/4e7d78f4dc23844c89ba49810fbb58fa to your computer and use it in GitHub Desktop.
Save stansidel/4e7d78f4dc23844c89ba49810fbb58fa to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <utility>
#include <future>
#include <mutex>
#include <random>
#include <thread>
#include <chrono>
#include <sstream>
using namespace std;
chrono::milliseconds random_time() {
std::mt19937_64 eng{std::random_device{}()};
std::uniform_int_distribution<> dist{20, 200};
return chrono::milliseconds{dist(eng)};
}
template <typename T>
class Container {
public:
Container(T& value)
: ref_to_value(value)
{}
T& ref_to_value;
};
class MyClass {
public:
MyClass(string text)
: value(text)
{}
Container<string> GetContainer() {
return {value};
}
private:
string value;
};
#define NUM_ITERATIONS 100
int main() {
MyClass cls("Some text");
future<void> reader = async([&cls]() {
string& value = cls.GetContainer().ref_to_value;
for (size_t i = 0; i < NUM_ITERATIONS; ++i) {
cout << "Value (" << i << "): " << value << '\n';
this_thread::sleep_for(chrono::microseconds(random_time()));
}
});
future<void> writer1 = async([&cls]() {
for (size_t i = 0; i < NUM_ITERATIONS / 2; ++i) {
stringstream ss;
ss << "A new string 1-" << i;
this_thread::sleep_for(chrono::microseconds(random_time()));
cls.GetContainer().ref_to_value = move(ss.str());
cout << "Value updated to 1-" << i << '\n';
}
});
future<void> writer2 = async([&cls]() {
for (size_t i = 0; i < NUM_ITERATIONS / 2; ++i) {
stringstream ss;
ss << "A new string 2-" << i;
this_thread::sleep_for(chrono::microseconds(random_time()));
cls.GetContainer().ref_to_value = move(ss.str());
cout << "Value updated to 2-" << i << '\n';
}
});
writer1.get();
writer2.get();
reader.get();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment