Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
eae6047745bd2b7416cbbd2e5d218a6fe2ed1e0c
[simgrid.git] / examples / mutualExclusion / centralized / Coordinator.java
1 /*
2  * $Id$
3  *
4  * Copyright 2010. The SimGrid Team. All rights reserved. 
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the license (GNU LGPL) which comes with this package. 
8  */
9
10 package mutualExclusion.centralized;
11 import java.util.LinkedList;
12
13 import org.simgrid.msg.Msg;
14 import org.simgrid.msg.MsgException;
15 import org.simgrid.msg.Task;
16 import org.simgrid.msg.Process;
17
18
19 public class Coordinator extends Process  {
20         public Coordinator(String hostname, String name) throws HostNotFoundException {
21                 super(hostname, name);
22         }
23         LinkedList<RequestTask> waitingQueue=new LinkedList<RequestTask>();
24         int CsToServe;
25                 
26         public void main(String[] args) throws MsgException {
27                 CsToServe = Integer.parseInt(args[0]);
28                 Task task;
29                 while (CsToServe >0) {
30                         task = Task.receive("coordinator");
31                         if (task instanceof RequestTask) {
32                                 RequestTask t = (RequestTask) task;
33                                 if (waitingQueue.isEmpty()) {
34                                    Msg.info("Got a request from "+t.from+". Queue empty: grant it");
35                                         GrantTask tosend =  new GrantTask();
36                                         tosend.send(t.from);
37                                 } else {
38                                         waitingQueue.addFirst(t);
39                                 }
40                         } else if (task instanceof ReleaseTask) {
41                                 if (!waitingQueue.isEmpty()) {
42                                         RequestTask req = waitingQueue.removeLast();
43                                         GrantTask tosend = new GrantTask();
44                                         tosend.send(req.from);
45                                 }
46                                 CsToServe--;
47                                 if (waitingQueue.isEmpty() && CsToServe==0) {
48                                         Msg.info("we should shutdown the simulation now");
49                                 }
50                         }
51                 }
52         }
53 }