dimanche 23 août 2020

C++11 How to write a demo that can quickly reproduce the out-of-order execution of CPU instructions?

In C++11 Memory order, I think the examples are very clear, then I wrote a demo to reproduce the multi-threaded read/write disorder of atmoic variables in memory_order_relaxed. I took the code from cppreference and tried to get the case where r1=r2=42.

enter image description here

This is my code:

#include <atomic>
#include <iostream>
#include <map>
#include <thread>
#include <unistd.h>

using namespace std;

map<pair<int, int>, int> count;

atomic_int x(0), y(0);

void ThreadWorker1(int &r1) {
    r1 = y.load(std::memory_order_relaxed); // A
    x.store(r1, std::memory_order_relaxed); // B
    return;
}

void ThreadWorker2(int &r2) {
    r2 = x.load(std::memory_order_relaxed); // C
    y.store(42, std::memory_order_relaxed); // D
    return;
}

int Run() {
    int r1 = 0;
    int r2 = 0;
    x.store(0, std::memory_order_relaxed);
    y.store(0, std::memory_order_relaxed);

    thread work1(ThreadWorker1, ref(r1));
    thread work2(ThreadWorker2, ref(r2));
    work1.join();
    work2.join();

    count[make_pair(r1, r2)] += 1;

    if (r1 == r2 && r2 == 42) {
        cout << "Hit: " << r1 << ", " << r2 << endl;
        return 0;
    }
    return -1;
}

int main() {
    int cnt = 0;
    while (Run() != 0) {
        cnt += 1;
        if (cnt % 10000 == 0) {
            cout << cnt << endl;
        }
    }

    for (auto c : count) {
        cout << c.first.first << ", " << c.first.second << "->" << c.second << endl;
    }
    return 0;
}

Thr progress ran long enough and didn't get the r1=r2=42 scenario. (Not doubting, of course, that if you run long enough, you can theoretically get this result)

Now the question is, how to transform the demo, without affecting the "out-of-order semantics" on the basis of, to be able to increase the probability of out-of-order execution of the cpu, to be able to quickly obtain the results of r1 = r2 = 42.

Thanks~

Aucun commentaire:

Enregistrer un commentaire