In this article, we’ll discuss Semaphore, and types of Semaphore in detail with the help of examples. It is a concept in operating systems for the synchronization of concurrent processes. Each thread that needs a connection will acquire the semaphore for the duration of its use of a connection (which prevents too many threads asking for connections at once), but the pool object must also use synchronized blocks or methods when taking connections out of its internal collection or putting them back in, to prevent such things as losing track of connections or mistakenly handing the same connection to two different threads because they asked simultaneously. Semaphore S is an integer variable which apart from initialization is accessed only through two standard atomic operations: wait () and signal (). Semaphore is essentially a non-negative integer that is used to solve the critical section problem by acting as a signal. This is somewhat different from ordinary mutual exclusion or monitor locking, which is typically used to prevent more than one thread from simultaneously modifying the same variables and causing inconsistent results or program state.Ĭonsider, for example, a connection pool with a limit of 10 connections in it. Mutexes, on the other hand, have a semantics which is strictly related to mutual exclusion: only the process which locked the resource is allowed to unlock it. I used this code to demonstrate how 1 thread can use a Semaphore and the other thread will wait (non-blocking) until the Sempahore is available. A semaphore acts as a limiter of available resource pool depth for example, a semaphore with a capacity of 10 allows a maximum of 10 threads to acquire it at once, and any further threads that attempt to acquire it will block until one of the other threads releases it. Semaphores can be used to implement exclusive access to variables, however they are meant to be used for synchronization.
0 Comments
Leave a Reply. |