Tuesday, July 29, 2025

CST334: Week 5 (Week 29)

This week we learned about threads, concurrency, and locks.


We learned that a process has at least one thread and can have multiple threads. Each one has its own stack. Concurrency is when multiple threads are able to time share on a cpu. The threads aren’t actually running simultaneously on a single core since only one run at a time but they can time share. Sharing resources between threads while avoiding data corruption and undefined behavior can be a challenge. We learned how locking is a powerful solution to this problem. In one of our simple examples we discussed how in a situation with two threads, with both threads reading, writing, incrementing, and decrementing a global variable in a process, the variable’s state can become unpredictable. If a mutex is defined such that each process grabs the lock before R/W or modify operations, the value of the shared variable will be predictable and accurate.


Locks avoid race conditions where the value of a shared resource like a variable depends on which thread accesses or modifies it first. Determinism is when a program's output or behavior is able to be predicted based on the inputs and the code. Locks help ensure this as demonstrated with the race condition. Atomicity is implemented at the hardware and is necessary for locks to work. An operation is atomic if it executes on the CPU in one uninterruptible operation. We learned that the test-and-set instruction is one such operation. Without this hardware/ISA supported operation, mutexes would not work.


Lastly we learned about critical sections and considerations around blocking. Critical sections are portions of code that are executed between the lock and unlock operations. Ideally they should be as small as possible so that a thread does not hog CPU time. Blocking happens when a thread needs to wait for some resource to become available or for a task to complete. For example, a thread may block while waiting for data to be returned by a disk read operation.


We’re well beyond the days of single core CPUs being dominant in most devices and a lot of applications that we use everyday run with multiple threads. This section was very helpful in demystifying what happens under the hood.

No comments:

Post a Comment

CST370: Week 7 (Week 58)

 This week we covered non-comparison sorting, dynamic programming, Warshall's algorithm, Floyd's algorithm, Greedy Technique, and Pr...