summaryrefslogtreecommitdiff
path: root/sources/scala/concurrent/SyncChannel.scala
blob: 6cab7b2ad65ffa9926e62a2a6f3c635dde14198f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-04, LAMP/EPFL               **
**  __\ \/ /__/ __ |/ /__/ __ |                                         **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
** $Id$
\*                                                                      */

package scala.concurrent;


class SyncChannel[a] {
  private var data: a = _;
  private var reading = false;
  private var writing = false;

  def await(cond: => Boolean) = while (!cond) { wait() }

  def write(x: a) = synchronized {
    await(!writing);
    data = x;
    writing = true;
    if (reading) notifyAll();
    else await(reading)
  }

  def read: a = synchronized {
    await(!reading);
    reading = true;
    await(writing);
    val x = data;
    writing = false;
    reading = false;
    notifyAll();
    x
  }
}