避免花费很长时间来完成“太多牛奶"的情况 [英] Avoid taking a long time to finish the 'too much milk' scenario

查看:92
本文介绍了避免花费很长时间来完成“太多牛奶"的情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是解决牛奶过多问题"的简单方法

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);
    }

问题在于,action-1可能要花费大量时间才能完成,这使得等待获取互斥量的任何进程都需要等待很长时间.

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?

编辑:推荐答案

现实生活中的解决方案是留下您要去买牛奶的字样.

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.

这篇关于避免花费很长时间来完成“太多牛奶"的情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆