Parent directory
atomic.cpp
concur.cpp
Makefile
peterson.cpp
rel-acq.cpp
seq-cst-1.cpp
seq-cst-2.cpp
sharedptr.cpp
spin-lock.cpp
#include <iostream>
#include <chrono>
#include <thread>
#include <atomic>
using namespace std;
using namespace std::chrono;
struct wallet {
std::atomic<uint64_t> money {0};
operator uint64_t() const {
return money;
// return money.load(std::memory_order_relaxed);
}
wallet& operator++() {
++money;
// money.fetch_add(1, std::memory_order_relaxed);
return *this;
}
};
// Built-in types are lock-free on most systems.
static_assert(atomic<uint64_t>::is_always_lock_free);
void f(wallet& sum, uint64_t count) {
while (count--) {
++sum;
}
}
int main() {
constexpr uint64_t count = 1'000'000;
wallet sum;
auto time0 = high_resolution_clock::now();
{
jthread t1 { f, ref(sum), count };
jthread t2 { f, ref(sum), count };
}
auto time1 = high_resolution_clock::now();
auto dt = duration_cast<microseconds>(time1 - time0);
cout << "elapsed: " << dt.count() << " microsec\n";
cout << "result: " << sum << '\n';
}#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
using namespace std;
using namespace std::chrono;
struct wallet {
mutex m;
uint64_t money = 0;
operator uint64_t() const { return money; }
wallet& operator++() {
{
scoped_lock lck{m};
++money;
}
return *this;
}
};
void f(wallet& sum, uint64_t count) {
while (count--) {
++sum;
}
}
int main() {
constexpr uint64_t count = 1'000'000;
wallet sum;
auto time0 = high_resolution_clock::now();
{
jthread t1 { f, ref(sum), count };
jthread t2 { f, ref(sum), count };
}
auto time1 = high_resolution_clock::now();
auto dt = duration_cast<microseconds>(time1 - time0);
cout << "elapsed: " << dt.count() << " microsec\n";
cout << "result: " << sum << '\n';
}CC = g++
CXX = g++
CXXFLAGS = -Wall -g -std=c++20 -pthread -O3
LDFLAGS = -pthread
executables = concur atomic rel-acq seq-cst-1 seq-cst-2 peterson spin-lock sharedptr
objects = concur.o atomic.o rel-acq.o seq-cst-1.o seq-cst-2.o peterson.o spin-lock.o sharedptr.o
.PHONY: default
default: $(executables)
$(executables):
$(objects):
.PHONY: clean
clean:
rm -f a.out core $(executables) $(objects)
.PHONY: all
all: clean default#include <iostream>
#include <chrono>
#include <thread>
#include <atomic>
using namespace std;
using namespace std::chrono;
struct peterson_lock {
std::atomic<bool> flag[2] = {false, false};
std::atomic<int> turn = 0;
void lock(int self) {
int other = 1 - self;
// Declare my intent
flag[self].store(true, std::memory_order_seq_cst);
// Yield to other thread
turn.store(other, std::memory_order_seq_cst);
// Wait if the other thread has intent and it's their turn
while (flag[other].load(std::memory_order_seq_cst) &&
turn.load(std::memory_order_seq_cst) == other)
;
}
void unlock(int self) {
// Release my intent
flag[self].store(false, std::memory_order_seq_cst);
}
};
int main() {
uint64_t counter = 0;
peterson_lock mtx;
auto f = [&](int id) {
for (uint64_t i = 0; i < 1'000'000; ++i) {
mtx.lock(id);
++counter;
mtx.unlock(id);
}
};
{
jthread t0 { f, 0 }; // self=0, other=1
jthread t1 { f, 1 }; // self=1, other=0
}
cout << "result: " << counter << '\n';
}#include <atomic>
#include <cassert>
#include <thread>
const char* HELLO = "Hello, World!";
const char* data;
std::atomic<bool> ready;
void producer() {
data = HELLO;
// ready.store(true, std::memory_order_relaxed);
ready.store(true, std::memory_order_release);
}
void consumer() {
while (!ready.load(std::memory_order_acquire))
// while (!ready.load(std::memory_order_relaxed))
;
assert(data == HELLO);
}
int main() {
for (int i = 0; i < 10'000'000; ++i) {
data = nullptr;
ready = false;
std::thread t1(producer);
std::thread t2(consumer);
t1.join(); t2.join();
}
}#include <atomic>
#include <cassert>
#include <thread>
int main() {
std::atomic<int> x = 0;
std::atomic<int> y = 0;
bool x_set_before_y = false;
bool y_set_before_x = false;
std::thread write_x(
[&] {
x = 1;
}
);
std::thread write_y(
[&] {
y = 1;
}
);
std::thread read_x_then_y(
[&] {
while (x == 0)
;
if (y == 0)
x_set_before_y = true;
}
);
std::thread read_y_then_x(
[&] {
while (y == 0)
;
if (x == 0)
y_set_before_x = true;
}
);
write_x.join();
write_y.join();
read_x_then_y.join();
read_y_then_x.join();
assert(!(x_set_before_y && y_set_before_x));
}#include <atomic>
#include <barrier>
#include <cassert>
#include <cstddef>
#include <iostream>
#include <thread>
constexpr size_t iterations = 10'000'000;
template <typename F>
std::thread run_iterations(std::barrier<>& rendezvous, F f) {
return std::thread([&rendezvous, f] {
for (size_t i = 0; i < iterations; ++i) {
rendezvous.arrive_and_wait(); // wait for everyone to be ready
f();
rendezvous.arrive_and_wait(); // wait for everyone to finish
}
});
}
int main() {
// Ensure the atomics don't share cache lines
alignas(128) std::atomic<int> x;
alignas(128) std::atomic<int> y;
bool x_set_before_y;
bool y_set_before_x;
std::barrier<> rendezvous {5}; // 4 worker threads + main
std::thread write_x = run_iterations(rendezvous,
[&] {
x.store(1, std::memory_order_relaxed);
// x.store(1, std::memory_order_release);
}
);
std::thread write_y = run_iterations(rendezvous,
[&] {
y.store(1, std::memory_order_relaxed);
// y.store(1, std::memory_order_release);
}
);
std::thread read_x_then_y = run_iterations(rendezvous,
[&] {
while (x.load(std::memory_order_relaxed) == 0)
// while (x.load(std::memory_order_acquire) == 0)
;
if (y.load(std::memory_order_relaxed) == 0)
// if (y.load(std::memory_order_acquire) == 0)
x_set_before_y = true;
}
);
std::thread read_y_then_x = run_iterations(rendezvous,
[&] {
while (y.load(std::memory_order_relaxed) == 0)
// while (y.load(std::memory_order_acquire) == 0)
;
if (x.load(std::memory_order_relaxed) == 0)
// if (x.load(std::memory_order_acquire) == 0)
y_set_before_x = true;
}
);
for (size_t i = 0; i < iterations; ++i) {
x = 0;
y = 0;
x_set_before_y = false;
y_set_before_x = false;
rendezvous.arrive_and_wait(); // wait for workers to be ready
rendezvous.arrive_and_wait(); // wait for workers to finish
assert(!(x_set_before_y && y_set_before_x));
}
write_x.join();
write_y.join();
read_x_then_y.join();
read_y_then_x.join();
}
// TODO: The assert passes anyway because arm64 is multi-copy atomic: a store
// becomes visible to all other cores at once. Each reader's two ldapr loads are
// ordered, so c and d can't see x and y set in opposite orders. The extra
// seq_cst guarantee, a single total order that also covers store→load
// reordering, isn't needed for this test because no thread does a store
// followed by a load. The C++ memory model still allows this outcome with
// release/acquire, and POWER can exhibit it. So a pass on this machine doesn't
// prove the code is correct.#include <atomic>
#include <string>
#include <thread>
#include <cassert>
#include <iostream>
using namespace std;
/* SharedPtr changes
- atomic<int>* count
- no count if ptr is nullptr -> need null checks
- we did this so move could be noexcept. in general move should be noexcept,
and just in case thread uses move_ifnoexcept
- detach() factored out & release() so we dont have to assign to empty ptr
- added move so that thread doesnt hold a copy after passing it to functor
- relaxed inc and get_count() because no publishing
*/
template <typename T>
class SharedPtr {
public:
explicit SharedPtr(T* p = nullptr)
: ptr{p}, count{p ? new std::atomic<int>{1} : nullptr} {}
~SharedPtr() { detach(); }
// Copy constructor and assignment
SharedPtr(const SharedPtr<T>& sp) : ptr(sp.ptr), count(sp.count) {
if (count) count->fetch_add(1, std::memory_order_relaxed);
}
SharedPtr<T>& operator=(const SharedPtr<T>& sp) {
if (this != &sp) {
// first, detach.
detach();
// attach to the new object.
ptr = sp.ptr;
count = sp.count;
if (count) count->fetch_add(1, std::memory_order_relaxed);
}
return *this;
}
// Move constructor and assignment
SharedPtr(SharedPtr<T>&& sp) noexcept : ptr(sp.ptr), count(sp.count) {
sp.ptr = nullptr;
sp.count = nullptr;
}
SharedPtr<T>& operator=(SharedPtr<T>&& sp) noexcept {
if (this != &sp) {
// first, detach.
detach();
// attach to the new object.
ptr = sp.ptr;
count = sp.count;
sp.ptr = nullptr;
sp.count = nullptr;
}
return *this;
}
void release() {
detach();
ptr = nullptr;
count = nullptr;
}
T& operator*() const { return *ptr; }
T* operator->() const { return ptr; }
operator void*() const { return ptr; } // enables "if (sp) ..."
T* get_ptr() const { return ptr; } // access to underlying ptr
// access to reference count
int get_count() const {
return count ? count->load(std::memory_order_relaxed) : 0;
}
private:
void detach() {
// if (count && count->fetch_sub(1, std::memory_order_acq_rel) == 1) {
if (count && count->fetch_sub(1, std::memory_order_relaxed) == 1) {
delete ptr;
delete count;
}
}
T* ptr; // the underlying pointer
std::atomic<int>* count; // the reference count
};
struct X {
int x;
X() : x{0} {}
// X should be mutated before destruction
~X() { assert(x == 42); }
void mutate() { x = 42; }
// Copy and move not needed for this demo
X(const X&) = delete;
X& operator=(const X&) = delete;
X(X&&) = delete;
X& operator=(X&&) = delete;
};
int main() {
for (int i = 0; i < 100'000'000; ++i) {
SharedPtr<X> sp { new X{} };
std::jthread t1(
[](SharedPtr<X> sp1) {
assert(sp1.get_count() <= 2);
sp1->mutate();
sp1.release();
},
sp);
std::jthread t2(
[](SharedPtr<X> sp2) {
assert(sp2.get_count() <= 2);
sp2.release();
},
std::move(sp));
}
}#include <iostream>
#include <chrono>
#include <thread>
#include <atomic>
using namespace std;
using namespace std::chrono;
struct spin_lock {
std::atomic_flag flag;
void lock() {
while (flag.test_and_set(std::memory_order_acquire))
;
}
void unlock() {
flag.clear(std::memory_order_release);
}
};
int main() {
uint64_t counter = 0;
spin_lock mtx;
auto f = [&]() {
for (uint64_t i = 0; i < 1'000'000'000; ++i) {
mtx.lock();
++counter;
mtx.unlock();
}
};
{
jthread t0 { f };
jthread t1 { f };
}
cout << "result: " << counter << '\n';
}