Skip to content

Instantly share code, notes, and snippets.

@suyash
Last active December 15, 2016 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suyash/1d338c565d200217a185aa73901fcf97 to your computer and use it in GitHub Desktop.
Save suyash/1d338c565d200217a185aa73901fcf97 to your computer and use it in GitHub Desktop.
shared_mutex

< C++17

run shared_mutex.cc -lboost_system -lboost_thread -lpthread -std=c++14

C++17

CXX=g++-6 run shared_mutex.cc -lpthread -std=c++17
#include <chrono>
#include <thread>
#if __cplusplus > 201402L
#include <shared_mutex>
#else
#include <boost/thread/shared_mutex.hpp>
#endif
#if __cplusplus > 201402L
std::shared_mutex m;
#else
boost::shared_mutex m;
#endif
bool running = true;
int x = 0;
void read() {
#if __cplusplus > 201402L
std::shared_lock<std::shared_mutex> lock(m);
#else
boost::shared_lock<boost::shared_mutex> lock(m);
#endif
printf("starting reading\n");
printf("%d\n", x);
printf("ending reading\n");
}
void write() {
#if __cplusplus > 201402L
std::unique_lock<std::shared_mutex> lock(m);
#else
boost::unique_lock<boost::shared_mutex> lock(m);
#endif
printf("starting writing\n");
x++;
printf("ending writing\n");
}
int main() {
printf("__cplusplus: %ld\n", __cplusplus);
std::thread read_thread([]() {
while (running) {
read();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
});
std::thread write_thread([]() {
while (running) {
write();
std::this_thread::sleep_for(std::chrono::seconds(2));
}
});
std::this_thread::sleep_for(std::chrono::seconds(10));
running = false;
read_thread.join();
write_thread.join();
printf("OK\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment