Simpy如何在处理抢占原因后恢复抢占进程

Simpy how to resume a preempted process after handling the cause of preemption

我正在使用 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()

使用 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))

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