lundi 21 mars 2022

Is there an issue with "cache coherence" on C++ multi-threading on a *Single CPU* (Multi-Core) on Windows?

Is it possible (A single CPU case: Windows can run on top of Intel / AMD / Arm CPU), that thread-1 runs on core-1 store a bool variable (for example) and it stays in L1 cache, and thread-2 runs on core-n uses that bool variable, and it looks on another instance of it (the instance that is in the memory?

Code example (For demonstrating the issue, lets say that the std::atomic_bool was just a bool):

#include <thread>
#include <atomic>
#include <chrono>

std::atomic_bool g_exit{ false }, g_exited{ false };

using namespace std::chrono_literals;

void fn()
{
    while (!g_exit.load(std::memory_order_relaxed))
    {
        // do something (lets say it took 5s)
        std::this_thread::sleep_for(5s);
    }

    g_exited.store(true, std::memory_order_relaxed);
}

int main()
{
    std::thread wt(fn);
    wt.detach();

    // do something (lets say it took 2s)
    std::this_thread::sleep_for(2s);

    // Exit

    g_exit.store(true, std::memory_order_relaxed);

    for (int i = 0; i < 5; i++) { 
        std::this_thread::sleep_for(1s);
        if (g_exited.load(std::memory_order_relaxed)) {
            break;
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire