描述
模拟一个服务器server,多个客户端同时到达服务器,按照先来先服务(FCFS)的模式进行服务。服务器的并行度为2(相当于两个工作核心,同时服务2个客户端)。打印服务日志和队列情况。
准备工作
- Python 语言:2.7以上版本
- SimPy :2.3.1版本
- 学习SimPy中FIFO型队列资源(resource)的基本语法及工作模式;学习FIFO型队列资源的参数(主要理解capacity参数)、数据结构(主要理解activeQ ,waitQ)
参考程序
import SimPy.Simulation as Simulation
def Print_Q(q):
ls = ""
for i in range(len(q)):
ls += q[i].name + " "
return ls
class Client(Simulation.Process):
def __init__(self, name):
Simulation.Process.__init__(self, name)
def getServed(self, servtime, myServer):
print("%s requests a unit at t=%s" % (self.name, Simulation.now()))
yield Simulation.request, self, myServer
yield Simulation.hold, self, servtime
print("activeQ " + Print_Q(myServer.activeQ))
print("waitQ " + Print_Q(myServer.waitQ))
yield Simulation.release, self, myServer
print("%s serve done at t=%s" % (self.name, Simulation.now()))
Simulation.initialize()
server = Simulation.Resource(capacity=2, qType=Simulation.FIFO)
cl_list = []
for i in range(6):
c = Client(name="c" + str(i))
cl_list.append(c)
for cl in cl_list:
Simulation.activate(cl, cl.getServed(servtime=10, myServer=server))
Simulation.simulate(until=100)
程序运行结果
c0 requests a unit at t=0
c1 requests a unit at t=0
c2 requests a unit at t=0
c3 requests a unit at t=0
c4 requests a unit at t=0
c5 requests a unit at t=0
activeQ c0 c1
waitQ c2 c3 c4 c5
c0 serve done at t=10
activeQ c1 c2
waitQ c3 c4 c5
c1 serve done at t=10
activeQ c2 c3
waitQ c4 c5
c2 serve done at t=20
activeQ c3 c4
waitQ c5
c3 serve done at t=20
activeQ c4 c5
waitQ
c4 serve done at t=30
activeQ c5
waitQ
c5 serve done at t=30