Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories

Dining Philosophers using semaphores

Rather than putting a semaphore on the Philosopher, I suggest putting a semaphore on the Chopstick; the Philosopher calls acquire on the left and right chopsticks' semaphores and releases the chopsticks' semaphores when done. This would replace the ReentrantLock on the Chopstick.

To prevent deadlock, you can use tryAcquire(int permits, long timeout, TimeUnit unit) so that a Philosopher releases its left chopstick's semaphore if it fails to acquire its right chopstick's semaphores within a timeout; if you use a random timeout (e.g. between 100 and 500 milliseconds) then each Philosopher should eventually make progress.

Edit: Your new Chopstick code runs the risk of deadlock - all philosophers pick up their left chopstick and then wait forever for their right chopstick to be free. A tryAcquire will allow a philosopher to release its left chopstick if it can't acquire its right chopstick after a timeout, which will allow the philosopher to its left to proceed.

class ChopStick{
  private static Random random = new Random();

  // initialize with one permit
  private Semaphore sem = new Semaphore(1);

  public boolean pickUp(){
    try {
      // wait between 100 and 500 milliseconds
      return sem.tryAcquire(1, random.nextInt(400)
+ 100, TimeUnit.MILLISECONDS);
    } catch(InterruptedException e) {
      return false;

  public void putDown(){

class Philosopher extends Thread {
  public void run() {

  private void doEat() {
    if(ch1.pickup()) {
      if(ch2.pickup()) {
      else {
    else {

Categories : Java

Related to : Dining Philosophers using semaphores
Passing information to multiple threads in the dining philosopher's algorithm
The warning is simply means that an int is not necessarily the same size as a pointer on all platforms. To avoid the warning, you could declare i as an intptr_t. An intptr_t is guaranteed to be the same size as a pointer. But allow me to suggest an alternative solution. The code below demonstrates how to start multiple threads while passing a unique piece of information to each thread. The steps

Categories : C
How to use semaphores correctly
Yes, your semaphore is not used correctly. A semaphore instance can grant a number of permissions. A thread can acquire() a permission - block until a permission is available and then decrease the number of available permissions. A thread can release() a permission - increase the number of available permissions. In your code, each thread has its own semaphore with 11 permissions. Firstly, b

Categories : Java
Use semaphores for handling sockets in C
Once opened, a socket cannot be reopened, even if it is closed. You can create a similar, new socket, though. Either way, it is difficult to reliably determine whether a previously-opened socket has been closed, except by closing it. In any case, the usual paradigm does not require the kind of coordinating mechanism you ask about. Normally, one thread of one process would open the socket and h

Categories : C
Recently Add
Concurrent collection to 50/50 read/write
How to get unique members of object class (groupofUniqueNames) from an ldap server using java
Custom error reporting: how to log down function arguments (and possibly locals) in an exception handler?
Websphere MQ message redelivery
How to use BigDecimal to achieve following code instead of using double or float?
What exactly do the service() method of this HttpServlet?
Why does the Java API use int instead of short or byte?
Hibernate. One to one mapping without cross references
How to pass array to a java method
BooleanFieldEditor doesn't load value from PreferenceStore
NoClassDefFoundError when I call the class through commnad line
Shopizer Search
Java - Bank System + Transaction Function
Hadoop security using Apache DS / Apache Directory Studio
Multiple property-placeholder with overlapping locations does not work?
could not remove/add jpanel in jframe
Java garbage collection verbose not working
If child class has a variable with same name as private variable in parent what will be used?
Jackson parse json with a one-to-many relationship in a single step
Excel opens wrong view after generating in Apache POI
On Switch How to use logic operator on case JAVA
Java: What is the absolut first second in Calendar?
Waiting One Second for a button click, if button not clicked call function
Fastest way to extract part of a large JSON File
copy directory operation using linux command in java
Figuring out how to Format Printing
Why does @FunctionalInterface have a RUNTIME retention?
Collision detection Libgdx rectangles
Cannot find symbol in method changeRecL but declared in main method
Receiving " Connection reset" when connecting from dotnet client to a java server
© Copyright 2017 Publishing Limited. All rights reserved.