Logo AND Algorithmique Numérique Distribuée

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