Is it true that only a single thread can guarantee the linearizability?

4 weeks ago 19
ARTICLE AD BOX

Consider this example:

#include <atomic> #include <chrono> #include <thread> int main() { std::atomic<long int> key; auto t1 = std::thread([&]() { auto now = std::chrono::system_clock::now(); auto duration = now.time_since_epoch(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration).count(); key.store(seconds); // #1 occurred at timepoint `T1` }); auto t2 = std::thread([&]() { auto now = std::chrono::system_clock::now(); auto duration = now.time_since_epoch(); auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration).count(); key.store(seconds); // #2 occurred at timepoint `T2` }); auto t3 = std::thread([&]() { std::this_thread::sleep_for(std::chrono::milliseconds(300)); // debounce auto search_key = key.load(); // #3 occurred at timepoint `T3` // request(search_key); }); t1.join(); t2.join(); t3.join(); }

Assuming the case that each user's input will create a thread and calculate the user's input to produce a search key, then write it to key, there is a thread to read the user's input and make a network request for the loaded key. To avoid frequent network requests during the user's input, there is also a debounce mechanism in the search thread.

In this example, it models the user's two such input events, namely t1 and t2. Assuming every event occurred at the timepoint as specified by the comment and T1 < T2 < T3. Even though every atomic operation uses seq_cst and forms a single total order, and the timepoints T1 and T2 are both before T3, #3 can still load #1 and coherence-ordered before #2.

This is not linearizability, because T1 < T2 < T3 and the load at T3 didn't read the store that occurred at T2.(I'm not sure whether the consistency in the timeline can be called linearizability).

So, from the perspective of the C++ standard, is it true that only a single thread can guarantee linearizability? That is, the load operation is guaranteed to always read the store that occurred closest to the timeline before the load operation occurred.

Read Entire Article