Avoid taking a long time to finish the 'too much milk' scenario

三世轮回 提交于 2019-12-11 08:52:52

问题


The following is a simple solution to the 'too much milk problem'

    lock mutex;

    while (1){

        lock_acquire(mutex);

        if (no milk)
            go and buy milk;//action-1

        lock_release(mutex);
    }

The problem is that, action-1 can take a lot of time to accomplish, making any of the processes waiting to acquire the mutex to wait for a long time.

One way to avoid this is to have a timer so that the process buying milk will return with or without milk once the timer goes off. As you can see, there are problems with this. (e.g: there is no way to identify whether the process has already bought milk and on its way home)

Is there a better solution to this?

EDIT: The Too Much Milk Problem


回答1:


The solution in real life is to leave a note that you've gone out to buy milk.

Now, in programming, this doesn't quite solve things, only mitigates the risk of a race condition, since both Jack and Jill look at the fridge when it's empty, and both leave the note. But if you made the leave-note-if-no-milk-and-no-note part locked, then you're set. The time it takes to leave the note is very short compared to going out and buying milk.



来源:https://stackoverflow.com/questions/51584828/avoid-taking-a-long-time-to-finish-the-too-much-milk-scenario

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!