jeudi 27 août 2020

Is the following code thread unsafe? Is so, how can I make a possible result more likely to come out?

Is the screen output of the following program deterministic? My understanding is that it is not, as it could be either 1 or 2 depending on whether the latest thread to pick up the value of i picks it up before or after the other thread has written 1 into it.

On the other, hand I keep seeing the same output as if each thread waits the previous to finish, as in I get 2 on screen in this case, or 100 if I create similar threads from t1 to t100 and join them all.

If the answer is no, the result is not deterministic, is there a way with a simple toy program to increase the odds that the one of the possible results comes out?

#include <iostream>
#include <thread>

int main() {

    int i = 0;

    std::thread t1([&i](){ ++i; });
    std::thread t2([&i](){ ++i; });

    t1.join();
    t2.join();

    std::cout << i << '\n';
}

(I'm compiling and running it like this: g++ -std=c++11 -lpthread prova.cpp -o exe && ./exe.)

Aucun commentaire:

Enregistrer un commentaire