Enlico
Enlico

Reputation: 28416

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.)

Upvotes: 0

Views: 28

Answers (1)

Rami
Rami

Reputation: 184

Your are always seeing the same result because the first thread starts and runs its operations before the second one. This narrows the window for a race condition to occur.

But ultimately, there is still a chance that it occurs because the ++ operation is not atomic (read value, then increment, then write).

If the two threads start at the same time (eg: thread 1 slowed down due to the CPU being busy), then they will read the same value and the final result will be 1.

Upvotes: 3

Related Questions