Data races in Python, despite the Global Interpreter Lock
The article mixes up data races and race conditions, which is understandable since it&#x27;s a common mistake. Race conditions are a fairly general class of bugs involving some non-deterministic sequence of operations, but a data race is a very specific scenario (within a given memory model) that occurs when there are two or more concurrent accesses to a memory location and at least one of them is a write. Ignoring C extensions, the GIL absolutely does protect against this and data races are not possible in Python.<p>The bug is due to the fact that an operation such as &quot;x = x + 1&quot; 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&#x2F;writes is non-deterministic. A data race would be if the memory location that x represents is written to simultaneously as it&#x27;s being read from which could result in a form of clobbering.<p>To make this more concrete, given the following code:<p>print(x)<p>x = x + 1<p>print(x)<p>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&#x27;s addition is in the process of clearing out the higher bits so that at the completion of both threads, x&#x27;s bits are reset to 0. Such a scenario is not possible in Python.<p>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.