added Mailbox, as in ML;
authorwenzelm
Thu, 24 Apr 2014 12:10:26 +0200
changeset 56693 0423c957b081
parent 56692 8219a65b24e3
child 56694 c4e77643aad6
added Mailbox, as in ML;
src/Pure/Concurrent/mailbox.scala
src/Pure/build-jars
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/Pure/Concurrent/mailbox.scala	Thu Apr 24 12:10:26 2014 +0200
@@ -0,0 +1,37 @@
+/*  Title:      Pure/Concurrent/mailbox.scala
+    Module:     PIDE
+    Author:     Makarius
+
+Message exchange via mailbox, with non-blocking send (due to unbounded
+queueing) and potentially blocking receive.
+*/
+
+package isabelle
+
+
+import scala.collection.immutable.Queue
+
+
+object Mailbox
+{
+  def apply[A]: Mailbox[A] = new Mailbox[A]()
+}
+
+
+class Mailbox[A] private()
+{
+  private val mailbox = Synchronized(Queue.empty[A])
+  override def toString: String = mailbox.value.mkString("Mailbox(", ",", ")")
+
+  def send(msg: A): Unit =
+    mailbox.change(_.enqueue(msg))
+
+  def receive: A =
+    mailbox.guarded_access(_.dequeueOption)
+
+  def receive_timeout(timeout: Time): Option[A] =
+    mailbox.timed_access(_ => Some(Time.now() + timeout), _.dequeueOption)
+
+  def await_empty: Unit =
+    mailbox.guarded_access(queue => if (queue.isEmpty) Some(((), queue)) else None)
+}
--- a/src/Pure/build-jars	Thu Apr 24 12:09:55 2014 +0200
+++ b/src/Pure/build-jars	Thu Apr 24 12:10:26 2014 +0200
@@ -11,6 +11,7 @@
 declare -a SOURCES=(
   Concurrent/counter.scala
   Concurrent/future.scala
+  Concurrent/mailbox.scala
   Concurrent/simple_thread.scala
   Concurrent/synchronized.scala
   General/antiquote.scala