Async Techniques and Examples in Python Transcripts
Chapter: Thread safety
Lecture: Demo: A missed lock in our bank (global)
0:00 Now as I wrapped up that last presentation
0:02 I realized there's one more thing.
0:04 We actually have a little, somewhat small
0:06 but still, little bit of a bug in this program.
0:10 So remember our safe bank, it works correctly now
0:13 it's a tiny bit slower, but it actually works correctly
0:16 which is perfect.
0:17 And we did this by adding a coarse grain lock
0:20 everywhere we were doing the transfers.
0:22 So down here, we use this lock
0:25 and we block out access to this.
0:26 Heres' the thing though, we need to make sure that no
0:29 other thread can interact with these two accounts
0:31 while this is happening
0:33 and in this new transfer everything's fine
0:35 but remember validate_bank()?
0:37 We're also interacting with the account here.
0:40 So we need to be super careful
0:42 that we also take the lock there.
0:45 So basically the idea is
0:46 anywhere we're going to interact with the accounts
0:48 we have to also take these locks
0:50 assuming that's going to happen concurrently.
0:52 So we'll say with transfer_lock:.
0:56 Like this. Here we go.
1:00 Run it again, it is a tiny bit slower
1:03 because we're taking the locks more frequently.
1:05 We could actually, the reason is, every single transfer
1:09 we're calculating this is validate here.
1:11 We don't have to calculate that frequently
1:13 we could do some kind of other check
1:14 but I'm just going to leave it like this
1:16 not make any major changes
1:18 but we technically have a little bug on line 83 here
1:21 because we were accessing the accounts
1:24 specifically the account balance for the accounts that
1:26 were being transferred potentially between.
1:29 It just so happened that that wasn't happening very often
1:32 whereas this takes a little bit of time mostly
1:36 because of that sleep
1:37 this was so fast we actually never hit it but it was a bug
1:40 one more time, see everything's good. Perfect. Works great.