Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • C++

Idiom #33 Atomically read and update variable

Assign to the variable x the new value f(x), making sure that no other thread may modify x between the read and the write.

#include <atomic>
std::atomic<int> x{};

auto local_x = x.load();
while(!x.compare_exchange_strong(local_x, f(local_x))) {
	local_x = x.load();
}

I'm a bit unclear on whether the example is asking for an atomic value or something projected with a lock; I've shown an atomic.
#include <mutex>
//declaration
auto mutex = std::mutex{};
auto x = someValue();

//use
{
	auto lock = std::unique_lock{mutex};
	x = f(x);
}

Works for every type of x
(def x (atom 0))
(def f inc)
(swap! x f)

New implementation...
< >
programming-idioms.org