summaryrefslogtreecommitdiff
path: root/sources/examples/pilib/semaphore.scala
diff options
context:
space:
mode:
authorcremet <cremet@epfl.ch>2003-08-26 15:28:51 +0000
committercremet <cremet@epfl.ch>2003-08-26 15:28:51 +0000
commit80d3a625a75ba054eef58eac94dc3a8066690c36 (patch)
treeccdc5d3d86415b7630666961d2741589cf59dede /sources/examples/pilib/semaphore.scala
parent4c10e8515b2d1b7991f660b444f4b0a5d014286d (diff)
downloadscala-80d3a625a75ba054eef58eac94dc3a8066690c36.tar.gz
scala-80d3a625a75ba054eef58eac94dc3a8066690c36.tar.bz2
scala-80d3a625a75ba054eef58eac94dc3a8066690c36.zip
- Added "PiLib" library and associated examples.
- Fixed some files in the package "scala.concurrent".
Diffstat (limited to 'sources/examples/pilib/semaphore.scala')
-rw-r--r--sources/examples/pilib/semaphore.scala70
1 files changed, 70 insertions, 0 deletions
diff --git a/sources/examples/pilib/semaphore.scala b/sources/examples/pilib/semaphore.scala
new file mode 100644
index 0000000000..f1f454e239
--- /dev/null
+++ b/sources/examples/pilib/semaphore.scala
@@ -0,0 +1,70 @@
+/** Solution of exercise session 6 (first question). */
+object semaphore {
+
+ import scala.concurrent.pilib._;
+
+ class Signal extends Chan[unit] {
+ def send = write(());
+ def receive = read;
+ }
+
+ /** Interface. */
+ trait Semaphore {
+ def get: unit;
+ def release: unit;
+ }
+
+ /** First implementation. */
+ class Sem1 extends Semaphore {
+
+ private val g = new Signal;
+ private val r = new Signal;
+
+ def get: unit = g.send;
+ def release: unit = r.send;
+
+ private def Sched: unit = choice (
+ g * (x => { r.receive; Sched }),
+ r * (x => Sched)
+ );
+ spawn< Sched >;
+ }
+
+ /** Second implementation. */
+ class Sem2 extends Semaphore {
+
+ private val a = new Signal;
+ private val na = new Signal;
+
+ def get: unit = { a.receive; spawn< na.send > }
+ def release: unit = choice (
+ a * (x => spawn< a.send >),
+ na * (x => spawn< a.send >)
+ );
+ spawn< a.send >;
+ }
+
+ /** Test program. */
+ def main(args: Array[String]): unit = {
+ val random = new java.util.Random();
+ val sem = new Sem2;
+ def mutex(def p: unit): unit = { sem.get; p; sem.release }
+
+ spawn< {
+ Thread.sleep(1 + random.nextInt(100));
+ mutex( {
+ System.out.println("a1");
+ Thread.sleep(1 + random.nextInt(100));
+ System.out.println("a2")
+ } )
+ } | {
+ Thread.sleep(1 + random.nextInt(100));
+ mutex( {
+ System.out.println("b1");
+ Thread.sleep(1 + random.nextInt(100));
+ System.out.println("b2")
+ } )
+ } >;
+ }
+}
+