Avoid taking a long time to finish the 'too mu

2019-07-29 16:34发布

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条回答
贪生不怕死
2楼-- · 2019-07-29 17:05

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.

查看更多
登录 后发表回答