Skip to content

Instantly share code, notes, and snippets.

@qis
Last active December 18, 2020 13:58
Show Gist options
  • Save qis/c4d50381653d3fe22de557f70d5385aa to your computer and use it in GitHub Desktop.
Save qis/c4d50381653d3fe22de557f70d5385aa to your computer and use it in GitHub Desktop.
// https://en.cppreference.com/w/cpp/thread/shared_mutex
// https://godbolt.org/z/eoqErv
#include <iostream>
#include <shared_mutex>
#include <thread>
#include <vector>
int g_value = 0;
std::shared_mutex g_mutex;
void Print(std::thread::id id, bool set, bool start) {
static std::mutex m;
std::lock_guard lock{ m };
std::cout << "[" << (start ? '+' : ' ') << "] " << (set ? "set" : " ") << " thread: " << id << std::endl;
}
int GetValue() {
std::shared_lock lock{ g_mutex };
Print(std::this_thread::get_id(), false, true);
std::this_thread::sleep_for(std::chrono::seconds{ 2 });
Print(std::this_thread::get_id(), false, false);
return g_value;
}
void SetValue(int value) {
std::unique_lock lock{ g_mutex };
Print(std::this_thread::get_id(), true, true);
std::this_thread::sleep_for(std::chrono::seconds{ 3 });
Print(std::this_thread::get_id(), true, false);
}
int main(int argc, char* argv[]) {
std::vector<std::thread> threads;
threads.emplace_back([]() {
while (true) {
SetValue(1);
std::this_thread::sleep_for(std::chrono::milliseconds{ 100 });
}
});
for (auto i = 0; i < 3; i++) {
threads.emplace_back([]() {
while (true) {
GetValue();
std::this_thread::sleep_for(std::chrono::milliseconds{ 100 });
}
});
}
for (auto& thread : threads) {
thread.join();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment