Browse files

new files (missed them in last commit)

  • Loading branch information...
1 parent c6ecc43 commit 17ff19c753be5586f761fa6b4e4bd423d2d835a2 @krestenkrab committed Mar 18, 2010
Showing with 106 additions and 0 deletions.
  1. +94 −0 src/kilim/Lock.java
  2. +6 −0 src/kilim/MessageConsumer.java
  3. +6 −0 src/kilim/MessageProducer.java
View
94 src/kilim/Lock.java
@@ -0,0 +1,94 @@
+package kilim;
+
+import java.util.LinkedList;
+
+/**
+ * Simple reentrant lock that uses Kilim's means for suspending
+ *
+ * @author krab@trifork.com
+ */
+public class Lock implements PauseReason, EventPublisher {
+
+ Task owner = null;
+ int count;
+ LinkedList<Task> waiters;
+
+ static boolean $isWoven = true;
+
+ public void lock() throws Pausable {
+ Task.errNotWoven();
+ }
+
+ public void lock(Fiber f) {
+ while (!lock(f.task)) {
+ f.down();
+ Task.pause(this, f);
+ if(f.up() == Fiber.PAUSING__NO_STATE) {
+ f.setState(this, 0);
+ }
+ }
+ }
+
+ private boolean lock(Task currentTask) {
+ synchronized (this) {
+ if (owner == null) {
+ owner = currentTask;
+ count = 1;
+ return true;
+ } else if (owner == currentTask) {
+ count = count + 1;
+ return true;
+ } else {
+ addListener(currentTask);
+ return false;
+ }
+ }
+ }
+
+ private synchronized Task _unlock(Task currentTask) {
+ Task next = null;
+
+ if (owner != currentTask) {
+ throw new IllegalStateException();
+ }
+
+ if ((count = count-1) == 0) {
+ owner = null;
+ if (waiters != null && !waiters.isEmpty()) {
+ next = waiters.removeFirst();
+ }
+ }
+
+ return next;
+ }
+
+ public void unlock() throws Pausable {
+ Task.errNotWoven();
+ }
+
+ public void unlock(Fiber f) {
+ Task next = _unlock(f.task);
+ _unlock2(next);
+ }
+
+ private void _unlock2(Task next) {
+ if (next != null) {
+ next.resume();
+ }
+ }
+
+ private void addListener(Task eo) {
+ if (waiters == null) {
+ waiters = new LinkedList<Task>();
+ }
+
+ waiters.add(eo);
+ }
+
+ public boolean isValid(Task t) {
+ synchronized(this) {
+ return waiters != null && waiters.contains(t);
+ }
+ }
+
+}
View
6 src/kilim/MessageConsumer.java
@@ -0,0 +1,6 @@
+package kilim;
+
+public interface MessageConsumer {
+ void messageAvailable(Mailbox pub);
+ void consumeTimeout(Mailbox pub);
+}
View
6 src/kilim/MessageProducer.java
@@ -0,0 +1,6 @@
+package kilim;
+
+public interface MessageProducer {
+ void spaceAvailable(Mailbox src);
+ void produceTimeout(Mailbox pub);
+}

0 comments on commit 17ff19c

Please sign in to comment.