Logo AND Algorithmique Numérique Distribuée

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