Async Techniques and Examples in Python Transcripts
Chapter: Thread safety
Lecture: Demo: A missed lock in our bank (global)

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Now as I wrapped up that last presentation I realized there's one more thing. We actually have a little, somewhat small
0:07 but still, little bit of a bug in this program. So remember our safe bank, it works correctly now
0:14 it's a tiny bit slower, but it actually works correctly which is perfect. And we did this by adding a coarse grain lock
0:21 everywhere we were doing the transfers. So down here, we use this lock and we block out access to this.
0:27 Heres' the thing though, we need to make sure that no other thread can interact with these two accounts while this is happening
0:34 and in this new transfer everything's fine but remember validate_bank()? We're also interacting with the account here. So we need to be super careful
0:43 that we also take the lock there. So basically the idea is anywhere we're going to interact with the accounts we have to also take these locks
0:51 assuming that's going to happen concurrently. So we'll say with transfer_lock:. Like this. Here we go. Run it again, it is a tiny bit slower
1:04 because we're taking the locks more frequently. We could actually, the reason is, every single transfer we're calculating this is validate here.
1:12 We don't have to calculate that frequently we could do some kind of other check but I'm just going to leave it like this not make any major changes
1:19 but we technically have a little bug on line 83 here because we were accessing the accounts specifically the account balance for the accounts that
1:27 were being transferred potentially between. It just so happened that that wasn't happening very often whereas this takes a little bit of time mostly
1:37 because of that sleep this was so fast we actually never hit it but it was a bug one more time, see everything's good. Perfect. Works great.


Talk Python's Mastodon Michael Kennedy's Mastodon