1 /* Copyright (c) 2012-2014. The SimGrid Team.
2 * All rights reserved. */
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. */
7 package org.simgrid.msg;
8 /** A semaphore implemented on top of SimGrid synchronization mechanisms.
9 * You can use it exactly the same way that you use classical semaphores
10 * but to handle the interactions between the processes within the simulation.
14 public class Semaphore {
15 private long bind; // The C object -- don't touch it
17 * Semaphore capacity, defined when the semaphore is created. At most capacity
18 * process can acquire this semaphore at the same time.
20 protected final int capacity;
22 * Creates a new semaphore with the given capacity. At most capacity
23 * process can acquire this semaphore at the same time.
25 public Semaphore(int capacity) {
27 this.capacity = capacity;
29 /** The native implementation of semaphore initialization
31 private native void init(int capacity);
34 /** Locks on the semaphore object until the provided timeout expires
35 * @exception TimeoutException if the timeout expired before
36 * the semaphore could be acquired.
37 * @param timeout the duration of the lock
39 public native void acquire(double timeout) throws TimeoutException;
40 /** Locks on the semaphore object with no timeout
42 public void acquire() {
45 } catch (TimeoutException e) {
46 e.printStackTrace(); // This should not happen.
50 /** Releases the semaphore object
52 public native void release();
53 /** returns a boolean indicating it this semaphore would block at this very specific time
55 * Note that the returned value may be wrong right after the
56 * function call, when you try to use it... But that's a
57 * classical semaphore issue, and SimGrid's semaphores are not
58 * different to usual ones here.
60 public native boolean wouldBlock();
62 /** Returns the semaphore capacity
64 public int getCapacity(){
69 /** Deletes this semaphore when the GC reclaims it */
70 protected void finalize() throws Throwable {
73 private native void nativeFinalize();
75 * Class initializer, to initialize various JNI stuff
77 public static native void nativeInit();
79 org.simgrid.NativeLib.nativeInit();