Skip to content

Instantly share code, notes, and snippets.

@benloong
Created December 8, 2016 05:17
Show Gist options
  • Save benloong/5cadd56cbbc36e2a8448bfd3d58282a6 to your computer and use it in GitHub Desktop.
Save benloong/5cadd56cbbc36e2a8448bfd3d58282a6 to your computer and use it in GitHub Desktop.
Semaphore using c++11 condition_variable and mutex, SpinLock using atomic_flag
#include <future>
struct SpinLock {
std::atomic_flag spin_flag = ATOMIC_FLAG_INIT;
void lock() {
for (size_t k = 0; spin_flag.test_and_set(std::memory_order_acquire); k++)
{
if (k < 4)
{
continue;
}
int ns = 1;
if (k < 32)
{
ns = 0;
}
std::this_thread::sleep_for(std::chrono::nanoseconds(ns));
}
}
void unlock() {
spin_flag.clear(std::memory_order_release);
}
};
struct Semaphore
{
int count = 0;
std::condition_variable cond_var;
std::mutex mutex;
void wait() {
std::unique_lock<std::mutex> lock(mutex);
while (!count)
{
cond_var.wait(lock);
}
count--;
}
void notify() {
std::unique_lock<std::mutex> lock(mutex);
++count;
cond_var.notify_one();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment