85 points · by verdagon · 4y ago · 70 comments
The bug is due to the fact that an operation such as "x = x + 1" is not atomic, it can be interrupted at several points to allow for another thread to read and write to x. Each individual read and write is atomic, but the order of such reads/writes is non-deterministic. A data race would be if the memory location that x represents is written to simultaneously as it's being read from which could result in a form of clobbering.
To make this more concrete, given the following code:
print(x)
x = x + 1
print(x)
In Python it will always be the case that the first print statement prints a number that is less than the second print statement, guaranteed. However if data races were possible, it would be possible that the second print statement displays a number less than the first print statement. For example the first print statement could print 65535, and the second print statement could print out 0. This can happen if for example, two simultaneous additions occur where one addition is in the process of clearing out the lower bits at the same time that another thread's addition is in the process of clearing out the higher bits so that at the completion of both threads, x's bits are reset to 0. Such a scenario is not possible in Python.
Whether one considers data races to be race conditions is a matter of debate, but at any rate no one familiar with the difference between the two should consider the behavior in this article to be a data race.
Picture Thread A reading the value of X=0, then the Python scheduler preempts the thread. Then Thread B fetches and increments X three times. X is now 3. Thread A then runs again, and increments the value of X it had read previously, (0+1), then writes 1 to X.
The memory location just went: 0,1,2,3,1
I'm working on a series for my blog called Temporal Fuzzing that simulates these edge cases in a virtual machine. It is often very hard to predict the total set of possible behaviour given random interleavings.
(Edit: Apologies for misreading; our definitions are indeed similar, continued below)
In safe Rust data races are not possible and yet it is still possible for a Rust program to exhibit the behavior in your article, because your article is not an example of a data race but rather a race condition. Note that in the source you reference, it explicitly states that while data races are protected, race conditions are not.
The scenario I gave, where performing an operation such as "x = x + 1" can result in x decreasing in value can only be caused by an overflow, or a data race. No interpretation of a Python or safe Rust program will ever produce a decreasing value of x when evaluating "x = x + 1" (ignoring Rust's overflow behavior) since data races are not possible. In Java or C++, since data races are possible it is also possible that "x = x + 1" produces a decreasing value of x (that is not due to overflow).
Finally here is a good article that lays out the differences between data races and race conditions:
https://blog.regehr.org/archives/490
[1] https://doc.rust-lang.org/nomicon/races.html
[2] https://docs.oracle.com/cd/E19205-01/820-0619/geojs/index.ht...
The Python example has two concurrent accesses of the same memory (the global counter) where one of them is a write. That seems to meet the definition.
We're also seeing the telltale symptoms of a data race. Note that we don't need to see slicing to qualify as a data race; as plenty cache-line-aligned data races don't exhibit slicing (not implying you were claiming this, just mentioning it for anyone curious).
The Rustonomicon definition also adds "they are unsynchronized", perhaps that's the part we disagree on.
I see this code as unsynchronized; there is no mutex or atomic increment happening around this operation. One could reasonably disagree, depending on what level they're looking at: statement-level, instruction-level, opcode-level, assembly level, uop level, or a higher "logical" level.
Either way, the point of the article is to help debunk a common misperception that the GIL helps users with their concurrency in some way.
I'd be interested to see a concrete example of how it could actually happen on a real currently-deployed system. (I'm not saying people should normally write such code, but things do need to ground out in a concrete machine model at some point, even if it's just for the sake of implementing higher level language semantics.)
(Edit: replied to you with similar comment in sibling thread...)
A data race occurs when two memory accesses race, and at least one of them is a write. In C/C++, data races using non-atomic accessed are undefined behavior, and that's why those can be very bad and you definitely want to avoid those.
You can also have a data race using atomic accesses, but there the behavior (ignoring some of the issues with the C/C++ memory model) is well-defined, and therefore it is not by definition incorrect.
I would say that the Python code in the post does have a data race (since it has unsynchronized accesses to a variable, and at least one is a write). But the behavior of that code is still precisely defined (though non-deterministic), since Python just guarantees that you will see some interleaving of the individual atomic steps of each of the threads due to the GIL). Hence the data race in Python is not undefined behavior as in C/C++, and hence it does not have the same negative connotations. Basically, Python variable accesses behave like sequentially consistent atomic reads/writes in C/C++.
Note that data races in C/C++ being undefined behavior is in large part due to compiler optimizations and preventing accesses from being reordered by the compiler or the CPU. If you're working with 32-bit (or 64-bit) cacheline aligned memory accesses, then "clobbering" or "tearing" of memory accesses is not likely to be affect you, but your code can still be broken by reordering in the compiler or the CPU (either due to instruction reordering or caches/bus communication). Hence if you have a data race on say an int variable, you probably will never see 65536 there if you didn't write that value there, but you might see older/newer values than you would expect.
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.
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.
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.
Obviously, the fundamental issue with concurrency is programmer’s intent. This statement:
x += 1; y -= 1
can be interpreted in two ways: atomic {
x += 1
y -= 1
}
or atomic { x += 1 }
atomic { y -= 1 }
The best the compiler can do would be to alert the programmer of the ambiguity; I know of no compiler that does that. atomic { tmp = x + 1 }
atomic { x = tmp }
atomic { tmp = y - 1 }
atomic { y = tmp }
In fact I would expect this is the most likely possibility, at least for user defined objects. atomic tmp=x
atomic tmp+=1
atomic x=tmp
atomic tmp=y
atomic tmp-=1
atomic y=tmpThat sounds good and authoritative. Unfortunately the Python documentation itself is silent on the subject. And more importantly the Python community is filled with people who believe exactly the opposite.
It's a real hole. And the only solution right now is to tell everyone to avoid threads. The Python world simply isn't prepared for them.
FWIW: I'm one of a handful of people who have found and fixed race conditions in python scripts. And it was largely because my background is in racey C code and my eyes were primed to see it. And even then, I genuinely thought (based on incorrect advice like the above) that this sort of thing was impossible and kept looking before trying the obvious synchronization solution. And it was only then that I realized what a mess concurrency is in the mind of the modern python developer.
I used to think that it did as well, but then my C/Java brain kicked in and realized that couldn't be correct. I wrote this article to help others see it in action.
I did too. I even wrote multithreaded test programs to see if it was true: they would always give me consistent results on Python and Ruby but on Java and C data got clobbered as expected.
essentially the same operations in the same order, that need to be isolated (i.e. transactional / atomic) from concurrent threads performing the same operations.
The fact that "counter" gets modified between the read and the write doesn't imply that multiple accesses were happening simultaneously; it just means that accesses from different threads were getting interleaved. The GIL would only prevent the former but not the latter, since a thread can give up the GIL at any point between operations.
https://link.springer.com/referenceworkentry/10.1007/978-0-3...
Under the section 'General Races and Data Races', then 'Data race'. There's a definition of data races, in relation to general races.
"A data race is a special case of a general race. A data race exists between conflicting memory accesses..."
Why? Who defines that?
and yes, as everyone is saying, the gil keeps the python interpreter/runtime from ending up in an inconsistent state... its behavior should not be depended on by user programs. if you need to increment a counter, use a lock, or a counter that explicitly states that it's a thread safe atomic counter on the tin.
The Python documentation on threading and the GIL [1] makes it clear that the reason for the GIL is to make operations on Python objects inside the interpreter thread-safe, by ensuring that the C structures that store the states of Python objects can only be mutated by one thread at a time. All of those C-level operations happen "inside" a single bytecode. Python operations that require multiple bytecodes do not have any of the same guarantees.
[1] https://docs.python.org/3/c-api/init.html#thread-state-and-t...
As I understand it, yes, that has been one of the main obstacles to removing the GIL. The current way forward seems to be to make all the interpreter state per-thread, so that each thread could have a separate interpreter; this would make the GIL unnnecessary, but of course one would still need synchronization primitives like mutexes to control access to data shared between threads.
Case in point, here is the same race condition in Rust:
- playground[0] (see for yourself)
- inline code (not that long):
use std::thread;
use std::sync::atomic::AtomicU32;
use std::sync::atomic::Ordering;
static COUNTER : AtomicU32 = AtomicU32::new(0);
fn increase() {
for _i in 0..100000 {
let a = COUNTER.load(Ordering::SeqCst);
COUNTER.store(a + 1, Ordering::SeqCst);
}
}
fn main() {
let mut threads = Vec::new();
for _i in 0..400 {
threads.push(thread::spawn(increase))
}
for thread in threads {
thread.join().unwrap();
}
println!("Final counter: {}", COUNTER.load(Ordering::SeqCst))
}
The data races that Rust prevents are "instruction-level data races". They occur when a single, non atomic, architectural instruction is executed in parallel by multiple threads. In that case we can really get corrupted values, in that "partially written" value in the architectural sense (depending on architectural details) can be produced. Think a double word with one word rewritten by one thread and the other word rewritten by the other thread.In the given code example that is not an instruction-level data race, the produced value will strictly be in the range <max_number_of_increase>..<max_number_of_increase>*<number_of_threads> (plus or minus the usual off-by-one error), and no architectural artifacts can ever manifest.
I guess the insight of the article could be that `counter = counter + 1` is closer in Python from `a = atomicLoad(counter); atomicStore(counter, a + 1)` than from `atomicIncrement(counter)`?
I wonder if using `counter += 1` changes anything? In any case, I can see how it is easier to trigger accidental race conditions of that kind in Python than in Rust, with the atomic operations being implicit in the former, and explicit in the latter.
[0]: https://play.rust-lang.org/?version=stable&mode=release&edit...
If you replace the Python integer with a 0D NumPy array, and use a real in-place operation, the race disappears:
import numpy as np
counter = np.array(0, dtype=np.uint32)
one = np.uint32(1)
def increase():
global counter
for i in range(0, 100000):
counter += one
Of course, the lesson still holds: accessing shared state from multiple threads still requires care; you don’t get to ignore these things just because Python has a GIL. with GIL:
x = counter + 1
with GIL:
counter = xWhy ? I'm on Linux, using Python 3.10. It's only happening using Python2.7.
> Ironically, CPython 3.10 has gone the opposite direction and made thread scheduling much more deterministic. It now only releases the GIL on backwards edges in the byte code The example in the article always prints 40000000 in CPython 3.10! I expect this will ultimately make Python code less reliable in the future as many programs will accidentally depend on this behavior.
Here is an example what thread safe increment looks like in Python:
https://julien.danjou.info/atomic-lock-free-counters-in-pyth...
You need to lock it explicitly.
Note that `INC` instructor for x86 architecture needs explicit hints/locks as well, so this should suprise anyone:
Hypothetically, if Python had a built-in mutable integer type, the increment could be made atomic.
I learned very early on that python threads should be treated like C threads, and therefore should be avoided. Also there really isn't a performance gain to using threads (other than maybe waiting for IO completion).
1. Don't allow any undefined behavior or `unsafe` code in the language.
2. Record all inputs from FFI.
3. Carefully track the orderings of interactions across threads.
The article goes into the first two, but the third one is the most interesting IMO:
When we unlock a mutex or send a message, we assign a "sequence number" (similar to what we see in TCP packets).
Whenever we lock a mutex or receive a message, we read the sequence number and record it to this thread's "recording".
When replaying, we use that sequence number and that file to make sure we're reading in the same order as the previous execution.
An unexpected state would seem to break the memory model, and lead to corrupted data, wouldn't it?
It's kind of like a time-traveling debugger, but with stronger guarantees.
I'm particularly excited about combining this with concurrency, we'll never have to spend hours hunting down mysterious race conditions ever again!