Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Race Conditions

Give Feedback

In this lesson, you’ll learn that it’s very important to consider race conditions when you’re working with multi-threaded applications. A race condition happens when more than one thread is trying to access a shared piece of data at the same time.

00:00 In this lesson, let’s talk about something very important to consider when we’re working with multi-threaded applications—and these are race conditions.

00:10 Let’s say we have some shared data that two threads want to use at the same time. We have an account balance of $100, and we have a withdrawal thread on the left and a deposit thread on the right.

00:24 What happens when both of these threads try to access this shared data, the account balance, at the same time? We don’t really have a solid understanding of what the balance is.

00:36 It depends on how much we’re depositing and how much we’re trying to withdraw.

00:42 Let’s say the account balance was at $100 and somehow the withdrawal thread made it to that shared data before the deposit did. And this is a very possible and often common occurrence with multi-threading, as we’ve seen before, is that sometimes threads don’t finish and get executed in the order that we would expect.

01:04 This withdrawal thread made it to the balance before the deposit did, and this is going to result in some unexpected, confusing behavior that the user will have to experience. So this is really bad.

01:18 What we want to happen is the deposit thread to reach the balance first, so we can deposit $50, and then that thread can go and finish its execution. Then the withdrawal thread can now successfully withdraw $150, and then the balance gets updated to its correct amount.

01:39 So, if we go back here, we see the essence of what a race condition is. It’s when more than one thread is trying to access a shared piece of data at the same time.

Become a Member to join the conversation.