Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Semaphore of size 1 the best option?

If you have a resource that only once person should access at a time you could use a semaphore of size one or you could just use a single ReentrantLock instance?

What are the subtle difference that make one or the other the better decision?

like image 276
More Than Five Avatar asked Mar 28 '13 10:03

More Than Five


1 Answers

There are differences:

  1. Semaphores can be acquired by one thread and released by another thread. This way, one thread can signal another thread. Semaphores with count 1 can also be used for mutual exclusion. Locks on the other hand are used only for mutual exclusion.
  2. Semaphores are not reentrant. This means a thread cannot acquire a semaphore when the permits are exhausted even if it has been acquired by the same thread. Locks can be reentrant.
like image 62
Abs Avatar answered Oct 02 '22 00:10

Abs