[Programming Problem] The Dining Philosophers

[Problem Link]

  • Solution here is to add some `ordering` on the resources (i.e. forks) requested by the processes (i.e. the philosophers).
  • Identify the resource id’s (or fork id’s) that a philosopher is surround with
  • We make sure the process requests the `lower` id fork before the `higher` id fork to avoid deadlocks
  • Identify which fork (left or right) is the lower id fork and request in that order (i.e. first left then right first right then left)
  • Make sure mutex’s are held until forks are released
class DiningPhilosophers {
 
    private static ReentrantLock[] mutex = new ReentrantLock[] {
        new ReentrantLock(),
        new ReentrantLock(),
        new ReentrantLock(),
        new ReentrantLock(),
        new ReentrantLock(),
    };
 
    public DiningPhilosophers() {
 
    }
 
    // call the run() method of any runnable to execute its code
    public void wantsToEat(int philosopher,
                           Runnable pickLeftFork,
                           Runnable pickRightFork,
                           Runnable eat,
                           Runnable putLeftFork,
                           Runnable putRightFork) throws InterruptedException {
 
        int left = philosopher;
        int right = (philosopher-1) == -1 ? 4 : philosopher-1;
 
        if (Math.min(left, right) == left) {
 
            DiningPhilosophers.mutex[left].lock();
            DiningPhilosophers.mutex[right].lock();
            pickLeftFork.run();
            pickRightFork.run();
 
        } else {
 
            DiningPhilosophers.mutex[right].lock();
            DiningPhilosophers.mutex[left].lock();
            pickRightFork.run();
            pickLeftFork.run();
 
        }
 
 
        eat.run();
 
        putLeftFork.run();
        putRightFork.run();
        DiningPhilosophers.mutex[left].unlock();
        DiningPhilosophers.mutex[right].unlock();
    }
}

1,581 thoughts on “[Programming Problem] The Dining Philosophers

  1. I have to express some thanks to this writer just for rescuing me from this particular trouble. Right after looking out throughout the the net and coming across advice which were not powerful, I assumed my entire life was well over. Living without the answers to the issues you have fixed all through the review is a crucial case, as well as ones which might have in a wrong way damaged my career if I had not encountered the blog. Your own knowledge and kindness in playing with the whole lot was excellent. I don’t know what I would’ve done if I had not encountered such a solution like this. I can now relish my future. Thanks very much for the skilled and amazing guide. I won’t be reluctant to recommend the website to any person who wants and needs direction about this problem.

  2. I simply wanted to appreciate you again. I am not sure what I might have used in the absence of these ways documented by you concerning that area. This has been an absolute hard situation in my opinion, but understanding the very well-written strategy you handled it forced me to cry over happiness. I will be thankful for your support and in addition have high hopes you comprehend what an amazing job you’re putting in training the others with the aid of a web site. Most probably you’ve never encountered all of us.

  3. I needed to send you this very little word to be able to say thanks over again about the exceptional guidelines you’ve shown here. It is quite wonderfully open-handed with people like you giving without restraint all that a few people could have made available as an e-book to make some profit for themselves, certainly seeing that you could possibly have done it in the event you wanted. Those techniques as well served like the easy way to comprehend someone else have a similar desire just like my very own to know lots more concerning this problem. I am certain there are lots of more pleasurable occasions up front for people who read your site.

  4. My wife and i felt very lucky that Peter managed to finish off his reports through the ideas he grabbed from your very own web page. It’s not at all simplistic to just always be giving away guidance which usually most people could have been selling. So we fully understand we have you to be grateful to for that. All of the explanations you’ve made, the simple web site menu, the relationships you can make it easier to instill – it is everything incredible, and it’s making our son in addition to the family feel that this content is satisfying, and that’s seriously mandatory. Thanks for the whole thing!

  5. I want to get across my admiration for your generosity in support of all those that have the need for help on this situation. Your very own dedication to passing the solution up and down had been really beneficial and has all the time empowered many people like me to achieve their targets. Your insightful instruction means a lot a person like me and extremely more to my peers. Regards; from all of us.

  6. I want to express my love for your generosity in support of men who have the need for help on this one topic. Your personal dedication to passing the message up and down appears to be astonishingly advantageous and have frequently helped many people just like me to reach their objectives. Your important useful information implies so much a person like me and even more to my mates. Many thanks; from everyone of us.

  7. I would like to voice my love for your generosity for men who actually need guidance on the question. Your personal dedication to getting the solution all-around had been remarkably powerful and have allowed some individuals much like me to get to their desired goals. This invaluable advice signifies so much a person like me and far more to my office colleagues. Many thanks; from all of us.

  8. I have to voice my passion for your generosity supporting individuals who have the need for help on the subject. Your personal dedication to getting the message across turned out to be pretty valuable and have allowed workers like me to get to their aims. The important help means much to me and still more to my mates. Thank you; from each one of us.

  9. I simply needed to appreciate you once more. I’m not certain what I could possibly have sorted out without the smart ideas shared by you regarding such topic. It previously was a real frustrating situation in my view, but viewing the specialized technique you managed it made me to weep with fulfillment. I’m just happy for this guidance and even expect you realize what a great job you are providing teaching the others through the use of a site. Probably you’ve never met all of us.

  10. I would like to get across my affection for your kind-heartedness giving support to those people who require help with the question. Your personal commitment to passing the message all through had been remarkably advantageous and has truly enabled others just like me to arrive at their ambitions. Your personal valuable tutorial can mean a great deal to me and somewhat more to my mates. Best wishes; from all of us.

  11. I wish to point out my respect for your generosity in support of individuals that absolutely need assistance with in this theme. Your personal commitment to passing the message all through appears to be certainly significant and has frequently helped many people much like me to reach their dreams. Your own warm and friendly useful information denotes a great deal a person like me and extremely more to my office colleagues. Many thanks; from each one of us.

  12. Thank you so much for providing individuals with an exceptionally special chance to check tips from here. It’s always so superb plus stuffed with a great time for me and my office mates to search the blog at least 3 times in a week to find out the latest things you have got. Not to mention, I’m also at all times fascinated for the splendid points you give. Certain 2 points in this posting are ultimately the very best I’ve ever had.

  13. I just wanted to type a simple message to be able to appreciate you for those fabulous advice you are writing here. My prolonged internet research has at the end been honored with brilliant insight to exchange with my family members. I ‘d suppose that most of us readers actually are truly lucky to exist in a useful place with very many lovely people with useful tricks. I feel quite fortunate to have encountered the web pages and look forward to many more amazing moments reading here. Thanks a lot once more for all the details.

  14. Needed to draft you this very small remark to thank you so much as before for the striking principles you have featured at this time. This has been quite wonderfully generous with people like you to offer publicly exactly what a few people could possibly have offered as an electronic book to make some money for themselves, particularly since you might have done it in case you decided. Those suggestions additionally worked to be a good way to be sure that many people have similar dreams similar to my very own to learn great deal more in regard to this issue. I am sure there are millions of more pleasant sessions up front for those who check out your website.

  15. I am commenting to let you be aware of what a incredible experience my friend’s princess gained reading the blog. She learned so many issues, including how it is like to have a wonderful giving mindset to get other people easily thoroughly grasp specified hard to do matters. You undoubtedly exceeded her expectations. I appreciate you for supplying such great, trustworthy, explanatory and even fun guidance on your topic to Tanya.

  16. I must get across my respect for your generosity for those who require assistance with that subject matter. Your personal commitment to getting the solution all over had become extremely significant and have specifically permitted girls like me to reach their ambitions. Your new valuable report can mean a whole lot a person like me and even further to my office workers. Many thanks; from all of us.

  17. I want to point out my gratitude for your kindness in support of women who should have guidance on this important niche. Your real dedication to getting the message throughout came to be amazingly good and has continually empowered others much like me to reach their desired goals. The useful recommendations indicates so much to me and somewhat more to my mates. Best wishes; from each one of us.

  18. Can I simply say what a relief to search out somebody who really is aware of what theyre talking about on the internet. You positively know methods to bring a difficulty to mild and make it important. Extra folks must read this and perceive this side of the story. I cant consider youre no more standard because you definitely have the gift.

  19. I must voice my gratitude for your kind-heartedness in support of people that actually need assistance with in this subject. Your special dedication to passing the message along appears to be certainly helpful and have without exception encouraged men and women just like me to arrive at their endeavors. The warm and friendly guide entails a lot to me and even further to my fellow workers. Warm regards; from everyone of us.

  20. Needed to put you one little bit of word to thank you very much yet again considering the gorgeous opinions you have provided on this site. It’s tremendously generous with people like you to supply publicly exactly what most people would have supplied as an e book to end up making some bucks for themselves, even more so considering that you could have done it if you ever wanted. These techniques additionally served to be a easy way to know that someone else have similar dreams the same as my very own to know much more with reference to this condition. I know there are millions of more pleasant instances in the future for individuals who check out your site.

  21. Needed to send you a bit of word to give many thanks again with your wonderful tricks you have documented at this time. It was quite seriously generous of people like you to offer unhampered what exactly a few people could have offered for sale for an electronic book to help make some profit on their own, especially seeing that you could have done it in the event you considered necessary. Those concepts also served to provide a fantastic way to understand that the rest have the identical dream just as my own to grasp whole lot more around this matter. I believe there are many more pleasurable situations in the future for individuals that look over your website.

  22. I simply had to appreciate you yet again. I do not know the things I could possibly have gone through in the absence of these tips discussed by you relating to this theme. It had been an absolute traumatic matter for me, nevertheless seeing a skilled form you managed it forced me to leap over gladness. I am grateful for this assistance as well as hope that you comprehend what a great job that you are providing educating others thru your site. I know that you have never met all of us.

Leave a Reply to Samdwece Cancel reply

Your email address will not be published. Required fields are marked *