dexterous
dexterous

Reputation: 6526

where can I use counting semaphore in linux threads?

I am trying to understand the application of counting semaphore. I could see that generally, there is a race condition in threads. To avoid such problems,we use mutual exclusion. We always need only one thread to read the common resource, and the other threads should be blocked. This way, we serialize the access of the common resource. However, I am not able to understand, what should be the scenario where I can use the counting semaphore? Please provide me a good use case.

Upvotes: 0

Views: 1257

Answers (2)

Duck
Duck

Reputation: 27552

The most common use of counting semaphore is for allocating resources which have multiple but finite availability, as stark mentioned.

They can also be useful in constructing things like barriers and reader/writer locks. In a barrier you want each of N threads to reach a certain point before any can proceed. The start of a horse race, for instance. With a r/w lock you have multiple readers and one writer. You can see how a counting semaphore might be helpful in creating these.

Upvotes: 1

stark
stark

Reputation: 13189

In the general case you have T threads accessing R resources where T > R. You use a counting semaphore initialized to R to grant access of a thread to a resource. One example would be a multi-processor graphics subsystem, where R is the number of processors.

Note that a counting semaphore serves two purposes. The count indicates the number of free resources. The value returned by the atomic decrement operation is an index or token to which resource is acquired.

Upvotes: 1

Related Questions