【问题标题】:Simpy how to resume a preempted process after handling the cause of preemptionsimpy处理抢占原因后如何恢复抢占进程
【发布时间】:2020-05-13 04:32:42
【问题描述】:

我正在使用simpy学习离散事件模拟,我遇到了一些与抢占资源相关的问题,我需要在处理完(中断进程)后如何恢复抢占进程,这是我的代码:

import simpy 
def resource_user(name, env, resource, wait, prio):
    yield env.timeout(wait)
    with resource.request(priority=prio) as req:
        print('%s requesting at %s with priority=%s' % (name, env.now, prio))
        yield req
        print('%s got resource at %s' % (name, env.now))
        try:
            yield env.timeout(3)
        except simpy.Interrupt as interrupt:
            by = interrupt.cause.by
            usage = env.now - interrupt.cause.usage_since
            print('%s got preempted by %s at %s after %s' %
                (name, by, env.now, usage))

env = simpy.Environment()
res = simpy.PreemptiveResource(env, capacity=1)
p1 = env.process(resource_user(1, env, res, wait=0, prio=0))
p2 = env.process(resource_user(2, env, res, wait=1, prio=0))
p3 = env.process(resource_user(3, env, res, wait=2, prio=-1))
env.run()

【问题讨论】:

    标签: python simulation simpy


    【解决方案1】:

    使用 while 循环并更新剩余的时间:

        import simpy 
        def resource_user(name, env, resource, wait, prio):
            yield env.timeout(wait)
            timeLeft = 3
            while timeLeft>0:
                with resource.request(priority=prio) as req:
                    print('%s requesting at %s with priority=%s' % (name, env.now, prio))
                    yield req
                    print('%s got resource at %s' % (name, env.now))
                    try:
                        yield env.timeout(timeLeft)
                        timeLeft = 0
                        print('%s completed at time %g' % (name, env.now))
                    except simpy.Interrupt as interrupt:
                        by = interrupt.cause.by
                        usage = env.now - interrupt.cause.usage_since
                        timeLeft -= usage
                        prio -= 0.1 #bump my prio enough so I'm next
                        print('%s got preempted by %s at %s after %s' %
                               (name, by, env.now, usage))
    

    请注意,我们为被中断的进程提供了稍高的优先级,以便它在具有相同原始优先级的其他进程之前得到服务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-30
      • 1970-01-01
      • 2021-10-16
      相关资源
      最近更新 更多