Skip to content

Instantly share code, notes, and snippets.

@ifknot
Created January 1, 2018 00:50
Show Gist options
  • Save ifknot/c0b830ca60bf01b17ce8b96ce0955342 to your computer and use it in GitHub Desktop.
Save ifknot/c0b830ca60bf01b17ce8b96ce0955342 to your computer and use it in GitHub Desktop.
MCS Lock
#ifndef MCS_LOCK_H
#define MCS_LOCK_H
#include <cstdint>
#include <assert.h>
#include <atomic>
#include <thread>
#include <iostream>
#include "cache_info.h"
#include "cpu_relax.h"
namespace sync {
class mcs_lock {
struct mcs_node {
bool locked{true};
uint8_t pad1[CACHELINE_SIZE - sizeof(bool)];
mcs_node* next{nullptr};
uint8_t pad2[CACHELINE_SIZE - sizeof(mcs_node*)];
};
static_assert(sizeof(mcs_node) == 2 * CACHELINE_SIZE, "");
public:
void lock();
void unlock();
private:
std::atomic<mcs_node*> tail{nullptr};
static thread_local mcs_node local_node;
};
}
#endif // MCS_LOCK_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment