CST 334 - Week 5
This week, I learned about multi-thread code. Threads are helpful because they exist under a process and share the same virtual address. This way it does not have to start up another process and allows for concurrency. Concurrency offers benefits such as an IDE handling edits while background compilation is occurring. With this comes some risks of poor execution that could lead to problems. The critical section is where both threads run a code, meaning that piece of code accesses a shared resource. It is important to understand that two threads should not run at the same time in this section. Mutual exclusion is a condition that can help with this, by ensuring that at most, only one thread will be within a critical section at a time.
The race condition is when the output of a multi-threaded program depends on the relative speed or scheduling of the thread. It is something that should be avoided because it means there is a lack of consistency on the output of the program. Ensuring that only one thread is reading or writing shared data at a time can help avoid the race condition. This is where mutex operations become handy. It forces the other threads to slow down until the intended operation completes because whatever thread calls for a lock, has to be the one to unlock it.
A much safer option to locks would be a thread-safe counter. It uses a library which includes mutex in its struct. This helps "hide" its use in the application and takes away the reliance on the user implementing locks correctly. The example used here is to create a "counter" API that locks and unlocks the counter in the background. All the user have to do is use the counter in the application, and in the backend, it is as if the locking and unlocking occurs automatically.
Comments
Post a Comment