Async Techniques and Examples in Python Transcripts
Chapter: Thread safety
Lecture: Concept: Basic thread safety

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Let's close out this chapter by just talking about basic thread safety. We begin by importing threading, of course
0:08 and we saw that there's actually several types of locks you can create. In fact, there's a bunch of locks we haven't even spoken
0:14 about, like mutexes and semaphores and barriers and so on. There's all sorts of fairly-complicated stuff we can
0:20 get into. But, this works for basic thread safety and most of what you're doing. So we're going to create a lock and we're going to make sure
0:27 we use the reentrant lock, not the one you cannot reenter maybe you want that, you probably don't though.
0:34 And then we're going to do our potentially-unsafe operations using a context manager, so with that lock and then
0:42 in that block we're going to do things that we don't want other threads to see it's like a little privacy window for your data.
0:47 Remember, at the beginning we talked about that temporarily invalid state and that's effectively unavoidable
0:52 in our programs, that's just how programming works for languages like Python. So make sure you do them here, so other threads
0:59 can't come and see them, and also remember everywhere you're interacting with any of those data structures you have to
1:05 take that same lock, otherwise you might get into trouble. We saw we mostly fixed our application by taking the lock
1:12 in the do_transfer() part, but we overlooked putting the lock in the verify accounts. We got away with it, but not really, it would have
1:20 gotten us eventually, probably, at night on a weekend when we're going to get woken up or have to leave a party
1:27 to go fix some bug that happened on the server or something weird like that, right? So, you don't want that, you want to make sure you actually
1:33 write it all correctly first, so just make sure any data structures you work with in there, if they're used
1:38 elsewhere also take a lock in those locations. That's basic thread safety in Python.


Talk Python's Mastodon Michael Kennedy's Mastodon