Synchronization primitives: Mutex and Semaphore (Explanation for Semaphore) - Article 5
Hi Folks, In the previous article, we saw what is Mutex or Mutual Exclusion. If critical section code is thought of as a single resource, only one thread will be allowed to use that resource. In this article, we shall see what is a semaphore and the solutions to few synchronization problems using the semaphore. A semaphore is very simple and easy to understand but it can solve complex synchronization problems. It is just a integer variable that can be initialized to any integer value (Usually non-negative: >= 0). After that, it is shared by the threads (Or processes). After initialization, only two operations can be performed on the semaphore: Decrement and Increment. The pseudo code of usage is as below: Semaphore MySem; MySem = 3; // Share MySem between n threads say 10 threads Thread 1: // Some code here MySem.Increment(); // MySem++ // Some more code here MySem.Decrement(); // MySem-- Thread 2: // Some code here MySem.Decrement(); // MySem -- // Some...