Precision and Threading Locks
00:00 In the previous lesson, I showed two context managers from the standard library, one for using files, the other for scanning directories. In this lesson, I have two more context managers for you to see.
00:24 Floats should never be used for money. Let me show you why. Got to love that precision. This isn’t a Python thing, but a floating-point standard thing. Love it or hate it, it’s been around for a long time and decisions made back in the early days of computing are still affecting us.
This means that the code will wait here until all the threads are done. Okay, so that’s how the threads are set up. Now let’s see what’s actually being threaded. Back up to the top … this is the
02:55 Each thread is going to be calling this function. Inside of the function, I loop five times. Each time, I’m opening a file and reading its contents. It expects the contents to be a single integer. It then increments this integer, reopens the same file, and writes the new value.
03:14 You can think of this as the world’s simplest database. The thread then waits for a little bit and then starts the next loop. Remember that there are two threads attempting to do this series of actions at the same time. Before I continue, can you anticipate what will go wrong?
Let me show you what can be done about this. This is a slightly modified version of the code. In the new version, a thread lock is created. Inside of
.accumulate(), the thread lock is locked using a context manager. Now, only one thread at a time can execute the body of the
04:38 If thread 1 is doing something with the file, thread 2 will have to wait until the lock is released. Using a context manager here is really good practice. Forgetting to release a lock in your code can result in two threads being blocked and never running again.
Become a Member to join the conversation.