Skip to content

Instantly share code, notes, and snippets.

@milesrout
Last active August 29, 2015 14:18
Show Gist options
  • Save milesrout/7d72c509e690307a7279 to your computer and use it in GitHub Desktop.
Save milesrout/7d72c509e690307a7279 to your computer and use it in GitHub Desktop.
#include <stdatomic.h>
int count()
{
static atomic_flag mutex = ATOMIC_FLAG_INIT;
static unsigned volatile counter = 0;
unsigned volatile retval;
while (atomic_flag_test_and_set_explicit(&mutex, memory_order_acquire));
retval = ++counter;
atomic_flag_clear_explicit(&mutex, memory_order_release);
return retval;
}
#include <atomic>
int count()
{
static std::atomic_flag mutex; // automatically initialized
static unsigned volatile counter = 0;
unsigned volatile retval;
while (mutex.test_and_set(std::memory_order_acquire));
retval = ++counter;
mutex.clear(std::memory_order_release);
return retval;
}
#include <mutex>
int count()
{
static std::mutex mtx;
static unsigned counter = 0;
std::lock_guard<mutex> _(mtx); // automatically released when it goes out of scope
return ++counter; // automatically saves the return value then unlocks mutex then returns this value.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment