{"id":1207,"date":"2020-07-31T18:09:00","date_gmt":"2020-08-01T00:09:00","guid":{"rendered":"https:\/\/coderrect.com\/?p=1207"},"modified":"2022-04-18T09:15:11","modified_gmt":"2022-04-18T15:15:11","slug":"data-races-what-are-they-and-why-are-they-evil-part-1","status":"publish","type":"post","link":"https:\/\/coderrect.com\/data-races-what-are-they-and-why-are-they-evil-part-1\/","title":{"rendered":"Data Races, what are they, and why are they evil? – Part 1"},"content":{"rendered":"
\n\t\n\t\n\t\n\t
\n\t\t\n\t\t

Archives<\/h1>\n\t<\/div>\n<\/header>\n\n\n

Race Conditions and Data Races<\/h3>\n\n\n\n

Most readers will be aware of “Race Conditions”, or “Races”. They are a common cause of bugs when writing concurrent programs that are not seen in single-threaded programs.<\/p>\n\n\n\n

You might also hear about people talking about a type of bug known as a “Data Race”. They have caused quite a stir online recently when the accuracy of a simulation program for the COVID-19 pandemic was called into question<\/a> because of suspected potential “data races”.<\/p>\n\n\n\n

So, are data races the same as race conditions?<\/p>\n\n\n\n

Simply put, race conditions<\/em> and data races<\/em> are different. One is not even a subset of the other, which is a common misunderstanding<\/a> even among experienced developers given that they both have “race” in their names, and share similar code patterns.<\/p>\n\n\n\n

Race condition, according to its wiki page<\/a>:<\/p>\n\n\n\n

… is the condition of an electronics, software, or other system where the system’s substantive behavior is dependent on the sequence or timing<\/strong> of other uncontrollable events. It becomes a bug<\/strong> when one or more of the possible behaviors is undesirable.<\/p><\/blockquote>\n\n\n\n

This definition implies race condition is not inherently a bug. Race conditions are inevitable as long as concurrent events exist within a system. <\/p>\n\n\n\n

Consider the following example:<\/p>\n\n\n\n

Example 1<\/h5>\n\n\n\n
\n
\n
Thread 1\n\/\/ x is a shared variable\nx = 1\n\nprint x<\/pre>\n\n\n\n

<\/p>\n<\/div>\n\n\n\n

\n
Thread 2\n\/\/ x is a shared variable\n\nx = 999\n<\/pre>\n\n\n\n

<\/p>\n<\/div>\n<\/div>\n\n\n\n

There is clearly a race condition<\/em> going on, where the result of print x<\/code> is dependent on the sequence of assignments to x<\/code>. However, this behavior may be intended and would not be considered a bug if both results are acceptable outcomes.<\/p>\n\n\n\n

On the other hand, a data race<\/em> is clearly defined as a bug<\/strong>. A data race occurs when two conflicting memory accesses:<\/p>\n\n\n\n