top | item 30422921

(no title)

rwbhn | 4 years ago

Your statement about your sample code is incorrect - just confirmed it for myself (cpython 3.8.3 is what was handy). Just add those print statements to the example in the article (before/after labels make analysis easier) and also add a set of threads that just do 'x = 0'.

discuss

order

Kranar|4 years ago

If you have a thread decrease the value of x then of course it's possible for x to decrease in value. The point is if you have a bunch of threads where every thread only ever increases the value of x like in the article then in Python it will never be the case that the value of x decreases.

In languages were data races are possible you can have every thread only ever increment x, and yet x's value will decrease due to a data race.

Python's GIL will protect against data races, meaning that certain classes of bugs where a specific memory location takes on a completely arbitrary value will never be observed from a Python program.

Thorrez|4 years ago

As reitzensteinm points out, even if every thread does "x = x + 1", x can decrease.

x starts as 0.

Thread A evaluates x + 1, getting 1.

Thread B executes the full statement 100 times, setting x to 100.

Thread A finishes executing the statement, setting x to 1.

So x decreased from 100 to 1.

But I agree with you that this is a race condition, not a data race.

hedora|4 years ago

> In languages were data races are possible you can have every thread only ever increment x, and yet x's value will decrease due to a data race.

That would be a very strange language, or a very strange machine.

In particular integer reads and writes are atomic (though not necessarily well ordered) on x86, arm, etc, so you'd be hard pressed to get a C compiler to emit code that tears the reads or writes in a way that would lead to integer decrements.