Written below is a collection of my miscellaneous and scattered notes representing what I learned from this week:
- The difference between a thread and a process is that threads share the same memory whereas processes do not
- Thus, due to sharing the same memory, switching between threads is faster than when switching between processes
- Multiple threads can run at the same time within a program
- This can cause issues when threads interrupt and overwrite each other's steps (cause race issues)
- Part of this issue can be solved with a concept known as "locks"
- Locks is a general term for a mechanism that restricts/controls shared resources between threads
- A Mutex is a specific category of lock that deals with allowing only one thread to run at a time
- However, the benefit to using threads is due to parallelism (to speed up time by doing different parts of the task at the same time)
Also including what I wrote for this week's discussion topic:
"A program is said to be indeterminate when we do not know what the program's true outcome will be. For example, it might give us a random answer within a certain range/spectrum. This happens when internal processes can interfere with each other. A great example, based on this weeks reading, is when we run two threads at the same time (and thus leading to a race condition).
To provide greater detail, let's say we have two threads trying to update the same variable called "counter." Each thread is to add up the counter by 10 times. Intuitively we believe the final result should be 20 since two threads would mean 10 + 10 = 20. However, every time we run the program, we might get the answer as 17, or 19, or 18, etc. This is because one thread may interrupt the step of another thread before that thread completes its update (thus overwriting that thread's intended action). To provide a visual, let's say there are three steps that a thread will go through:
1. Read the counter
2. Add +1 to the counter
3. write the value back to the counter
This means before a thread can complete all three steps, another thread can interrupt it at any of these steps and overwrite over it (thus leading to an counter increment getting lost). This specific example is called a race condition because it depends on which of the thread gets to the steps first (and who interrupts each other first)."