简体   繁体   中英

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?

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.

Semaphore s are good for counting permits/releases, so if you have more than one resource, Lock etal. will not help you much. But if you have only one resource to guard, they are good enough.

Counting Semaphore Example: You have a protected object, with a restriction of not more than five threads are allowed to access it concurrently. In that case a counting semaphore of initial value 5 is the mathematical fit. Downey's Little book of Semaphores is one of the best reads to understand the constructs.

While it is true that this can be done with both synchronized and Semaphore you first must figure out how you will use this resource. If you use synchronized this means that you will have to watch on synchronization in threads:

public void run() {
  // some code
  synchronized (resource) {
    // use resource
  }
}

If you don't want to let threads watch for this (which is in my opinion better), use Semaphore in getter method of resource:

public Resource acquireResource() {
  // acquire semaphore
  return resource;
}

public void releaseResource() {
  // release semaphore
}

and in thread just do:

public void run() {
  // some code
  Resource resource = ResourceContainer.getResource();
  // do something with resource
  releaseResource();
}

You can add Object parameter to these methods just to compare if same object released semaphore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM