Hard
Seqlock write path called from two writer threads
The reader below uses the full seqlock check (retry while s1 is odd or s1 != s2), and readers expect p.a == -p.b. write() is now called concurrently from two writer threads with no writer-side lock. What is the consequence?
main.cpp
struct Pair { long a; long b; }; // invariant: a == -b
std::atomic<unsigned> seq{0};
Pair data;
void write(long v) { // called from TWO threads, no lock
seq.fetch_add(1, std::memory_order_relaxed); // odd: in progress
std::atomic_thread_fence(std::memory_order_release);
data.a = v;
data.b = -v;
seq.fetch_add(1, std::memory_order_release); // even: done
}
Pair read() {
Pair p; unsigned s1, s2;
do {
s1 = seq.load(std::memory_order_acquire);
p = data;
std::atomic_thread_fence(std::memory_order_acquire);
s2 = seq.load(std::memory_order_relaxed);
} while ((s1 & 1) || s1 != s2);
return p;
}49 of 51 in Concurrency