mardi 23 mars 2021

Does as-if rule allow this kind of execution reordering

As we know, the compiler or the CPU may reorder the execution as they want, only if they follow the as-if rule. For example, if we have such a piece of code:

C = A + B;
D = E + F;

The compiler or the CPU may execute D = E + F before C = A + B. I can understand that.

Now let's talk about another case.

Saying that I have two threads a and b. I want to set some marks while executing so that I can monitor the whole process of a and b.

queue q; // thread safe

void thread_a()
{
    // do something
    q.push("a - 1");
    // do something
    q.push("a - 2");
}

void thread_b()
{
    // do something
    q.push("b - 1");
    // do something
    q.push("b - 2");
}

My question is: since we have the as-if rule and the execution order may be reordered, does it mean that the messages in the q is not reliable? Meaning that the real execution order is a - 1, b - 1, b - 2 and a - 2 but in the q there might be a - 1, a - 2, b - 1 and b - 2? If this could happen, how should I design or which kind of techinque should I use to monitor the process of multi-threading?

Aucun commentaire:

Enregistrer un commentaire