Last active
August 29, 2015 14:18
-
-
Save milesrout/7d72c509e690307a7279 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <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; | |
} |
This file contains hidden or 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 <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; | |
} |
This file contains hidden or 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 <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