Created
October 9, 2019 10:47
-
-
Save stansidel/4e7d78f4dc23844c89ba49810fbb58fa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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