EDDYMENS

Last updated 2023-03-09 17:42:45

What Is Race Condition?

Table of contents

Definition

Race condition in software is the situation where the execution order falls out of the expected sequence.

Use Cases and Examples

Imagine you walk into a restaurant and you place an order. Let's assume the one responsible for bringing your food and the one who brings the bill are two different people who do not talk to each other.

The one responsible for bringing your bill knows that once a customer places an order they should get the food in 30 minutes tops.

In your case, your food arrives 10 minutes late, and so you ended up getting the bill before the food. This is a race condition.

In software land, the commonest form of race conditions is caused by some combination of parallel processing (multi-threading, subroutines, etc) and external resource requests (API calls, reading files, etc).

Let's look at some pseudo-code where we fetch data from 2 different sources and then merge them into one document for a user to download.

01: students = new thread('getFile', 'students.csv'); 02: teachers = new thread('getFile', 'teachers.csv'); 03: export teacher+student;

Looking at the code above, there is a chance we only get teacher or student data or non at all since we are using separate threads to fetch the data, and not guaranteed that the threads will be done before the execution gets to line 3 for export.

Summary

Race condition is one of the biggest problems when it comes to distributed computing and there are many different ways to combat this. For example, the use of eventual consistency in situations where reconciliation is done to patch up the results of an uncompleted process once it's finally done.

Here is another article you might like 😊 "Diary Of Insights: A Documentation Of My Discoveries"