Can the effect of a weakened memory effect be increased before the end of its service life?

Say, inside a C ++ 11 program, we have a main thread named A that starts an asynchronous thread named B. Inside thread B, we execute an atomic array with an atomic variable in memory order std::memory_order_relaxed. Then thread A connects to thread B. Then thread A starts another thread named C, which performs an atomic load operation with memory order std::memory_order_relaxed. Is it possible that the loaded content in stream C is different from the content written in stream B? In other words, does the unstable memory sequence propagate here even after the life of the thread?

To try this, I wrote a simple program and ran it with many attempts. The program does not report a non-compliance. I think since thread A messes up when the threads start, a mismatch cannot happen. However, I am not sure about that.

#include <atomic>
#include <iostream>
#include <future>

int main() {

    static const int nTests = 100000;
    std::atomic<int> myAtomic( 0 );

    auto storeFunc = [&]( int inNum ){
        myAtomic.store( inNum, std::memory_order_relaxed );
    };

    auto loadFunc = [&]() {
        return myAtomic.load( std::memory_order_relaxed );
    };

    for( int ttt = 1; ttt <= nTests; ++ttt ) {
        auto writingThread = std::async( std::launch::async, storeFunc, ttt );
        writingThread.get();
        auto readingThread = std::async( std::launch::async, loadFunc );
        auto readVal = readingThread.get();
        if( readVal != ttt ) {
            std::cout << "mismatch!\t" << ttt << "\t!=\t" << readVal << "\n";
            return 1;
        }
    }

    std::cout << "done.\n";
    return 0;

}
+2
source share
2 answers

Before portable streaming platforms usually offer you the ability to specify memory visibility or place explicit memory barriers, portable synchronization was performed exclusively with explicit synchronization (such as mutexes) and implicit synchronization.

, , , . , . , , , . , , .

, . , , . , , - , . . , .

SergeyA, - . , , , , . , , , , - , , . , .

+3

Source: https://habr.com/ru/post/1687581/


All Articles