模拟环网

时间:2016-03-03 07:15:11

标签: python simulation simpy

我正在尝试模拟令牌环,但到目前为止遇到了一些麻烦。我修改了一个简单的例子来得到这个:

import random
import simpy
import math

SIM_TIME = 1000     # Simulation time in minutes
TOTAL_BYTES = 0

class Ring(object):
    """
    Hosts have to request the token. When they get the token, they
    can be served.
    """
    def __init__(self, env):
        self.env = env
        self.token = simpy.Resource(env)

    def serve(self, host):
        global TOTAL_BYTES
        bytes = random.randint(64, 1518)
        TOTAL_BYTES += bytes
        yield self.env.timeout(bytes / 10e8 * 60)
        print("Ring served %s." % (host))


def host(env, name, ring):
    """The host process (each host has a ``name``) arrives at the ring
    (``ring``) and waits for a token.
    """
    print('%s enters the ring at %.2f.' % (name, env.now))
    with ring.token.request() as request:
        yield request

        print('%s is handed a token at %.2f.' % (name, env.now))
        yield env.process(ring.serve(name))


def setup(env, numberOfHosts, lmda):
    """Create a ring, a number of initial hosts."""
    # Create the ring
    ring = Ring(env)

    # Create n hosts
    for i in range(numberOfHosts):
        env.process(host(env, 'Host %d' % i, ring))

    # Create more packets for the hosts
    while True:
        yield env.timeout(nedTime(lmda))
        print("A new process has arrived at %s" % (i))


# Return a random number (negativeExponentiallyDistributedTime)
def nedTime(rate):
    u = random.random()
    return (-1 / rate) * math.log(1 - u)

# Create an environment and start the setup process
env = simpy.Environment()
env.process(setup(env, numberOfHosts=10, lmda=0.01))

# Execute!
env.run(until=SIM_TIME)

我的问题是:如何在模拟运行时始终将数据包传入主机。

我在设置中尝试了while True,但我认为这不是正确的地方。

另外,主机功能如何保存数据包缓冲区?我已尝试将host()函数转换为Host类,但现在已编译问题。

谢谢。

0 个答案:

没有答案