Async Techniques and Examples in Python Transcripts
Chapter: Thread safety
Lecture: Concept: Basic thread safety
0:00 Let's close out this chapter
0:01 by just talking about basic thread safety.
0:04 We begin by importing threading, of course
0:07 and we saw that there's actually several types of locks
0:10 you can create.
0:11 In fact, there's a bunch of locks we haven't even spoken
0:13 about, like mutexes and semaphores and barriers and so on.
0:16 There's all sorts of fairly-complicated stuff we can
0:19 get into. But, this works for basic thread safety and
0:22 most of what you're doing.
0:24 So we're going to create a lock and we're going to make sure
0:26 we use the reentrant lock, not the one you cannot reenter
0:31 maybe you want that, you probably don't though.
0:33 And then we're going to do our potentially-unsafe operations
0:37 using a context manager, so with that lock and then
0:41 in that block we're going to do things that
0:43 we don't want other threads to see
0:44 it's like a little privacy window for your data.
0:46 Remember, at the beginning we talked about that
0:48 temporarily invalid state and that's effectively unavoidable
0:51 in our programs, that's just how programming works
0:54 for languages like Python.
0:55 So make sure you do them here, so other threads
0:58 can't come and see them, and also remember everywhere you're
1:01 interacting with any of those data structures you have to
1:04 take that same lock, otherwise you might get into trouble.
1:08 We saw we mostly fixed our application by taking the lock
1:11 in the do_transfer() part, but we overlooked putting
1:14 the lock in the verify accounts.
1:16 We got away with it, but not really, it would have
1:19 gotten us eventually, probably, at night on a weekend
1:23 when we're going to get woken up or have to leave a party
1:26 to go fix some bug that happened on the server or
1:28 something weird like that, right?
1:30 So, you don't want that, you want to make sure you actually
1:32 write it all correctly first, so just make sure any
1:35 data structures you work with in there, if they're used
1:37 elsewhere also take a lock in those locations.
1:40 That's basic thread safety in Python.