Skip to content

Instantly share code, notes, and snippets.

@cybertxt
Last active September 23, 2021 06:13
Show Gist options
  • Save cybertxt/9a9077720c15fec89ed1f3fd91c9e91a to your computer and use it in GitHub Desktop.
Save cybertxt/9a9077720c15fec89ed1f3fd91c9e91a to your computer and use it in GitHub Desktop.
spinlock in c++11 based on atomic_flag
#ifndef _SPINLOCK_H_20170410_
#define _SPINLOCK_H_20170410_
#include <atomic>
class spinlock {
public:
spinlock() { m_lock.clear(); }
spinlock(const spinlock&) = delete;
~spinlock() = default;
void lock() {
while (m_lock.test_and_set(std::memory_order_acquire));
}
bool try_lock() {
return !m_lock.test_and_set(std::memory_order_acquire);
}
void unlock() {
m_lock.clear(std::memory_order_release);
}
private:
std::atomic_flag m_lock;
};
#endif//_SPINLOCK_H_20170410_
#include "spinlock.h"
#include <mutex>
#include <future>
#include <iostream>
#include <map>
spinlock lock;
int value = 0;
int loop(bool inc, int limit) {
std::cout << "Started " << inc << " " << limit << std::endl;
for (int i = 0; i < limit; ++i) {
std::unique_lock<spinlock> _lock(lock);
if (inc)
++value;
else
--value;
}
return 0;
}
int main() {
auto f = std::async(std::launch::async, std::bind(loop, true, 20000000));
loop(false, 10000000);
f.wait();
std::cout << value << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment