Skip to content

Instantly share code, notes, and snippets.

@odeblic
Last active July 27, 2017 11:34
Show Gist options
  • Save odeblic/e429fc5c65760ee242044d31aef65826 to your computer and use it in GitHub Desktop.
Save odeblic/e429fc5c65760ee242044d31aef65826 to your computer and use it in GitHub Desktop.
Shared mutex discovery
#include <mutex>
#include <shared_mutex>
#include <iostream>
template <typename M>
void test(M& mutex)
{
bool exclusive = false;
bool shared = false;
if (mutex.try_lock())
{
mutex.unlock();
exclusive = true;
}
if (mutex.try_lock_shared())
{
mutex.unlock_shared();
shared = true;
}
auto stringify = [](bool s) { return s ? "free" : "busy"; };
std::cout << "mutex status: X=" << stringify(exclusive) << ", S=" << stringify(shared) << "\n";
}
int main()
{
std::shared_mutex mutex;
test(mutex);
mutex.lock_shared();
test(mutex);
mutex.unlock_shared();
test(mutex);
std::cout << "============================\n";
test(mutex);
mutex.lock();
test(mutex);
mutex.unlock();
test(mutex);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment