Quiz
- Could you explain how threads "allow us to retain values between web requests"? Is that just because each thread can put values on the heap and retain them that way?
Yes, that's exactly right. For example, we've had a number of example apps (including the
likesexample) that have used an in-memory database (list or dictionary or something). That data lives in the heap and is shared by all the threads.To be honest, in development mode there's only one thread so I didn't need to worry about locking. If we had deployed that example, we would have to use locks or the code would not be thread-safe.
- besides
last_insert_id, is there anything that can break if two threads were to share the same database connection?Good question. All the locking/transaction stuff we talked about last time, like checking the number of available spots in a class and then decrementing the counter if there's a spot available.
- Still not sure I understand why it's cheaper to start a new
thread than to compile and run a program.
Well, we wouldn't compile it from scratch. Let's assume it's already compiled into an executable file sitting on disk and all we want to do is start it. For a new process:
- Allocate memory for the whole process, including executable code, heap and thread memory
- Load the executable from disk. This takes forever, because disks (even SSD drives) are slow.
- Initial resource tables (file descriptors, security/permission credentials)
- set up execution context. (New call stack and CPU register state, Process/Thread control block.)
For a thread, we can skip steps a-c because they've already been done. We only need step d.
So starting a thread is typically 10-100 times faster than starting a process.