summaryrefslogtreecommitdiff
path: root/src/library/scala/concurrent/Process.scala
blob: 537b6c120c15bdb4e966c6db49b3eec6c1d8ed19 (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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2006, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |                                         **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

// $Id$


package scala.concurrent;


object Process {

  def spawn(body: => Unit): Process = {
    val p = new Process(body);
    p.start();
    p
  }

  def spawn_link(body: => Unit): Process =
    self.spawn_link(body);

  def send(p: Process, msg: MailBox#Message) =
    p.send(msg);

  def receive[a](f: PartialFunction[MailBox#Message, a]): a =
    self.receive(f);

  def receiveWithin[a](msec: long)(f: PartialFunction[MailBox#Message, a]): a =
    self.receiveWithin(msec)(f);

  def self: Process =
    if (Thread.currentThread().isInstanceOf[Process])
      Thread.currentThread().asInstanceOf[Process]
    else
      error("Self called outside a process");

  def exit(p: Process, reason: AnyRef) =
    p.exit(reason);

}

class Process(body: => Unit) extends Actor() {
  private var exitReason: AnyRef = null;
  private var links: List[Process] = Nil;

  override def run() =
    try {
      body
    }
    catch {
      case _: java.lang.InterruptedException =>
        signal(exitReason)
      case (exitSignal) =>
        signal(exitSignal)
    };

  private def signal(s: MailBox#Message) =
    links.foreach { p: Process => p.send(Triple('EXIT, this, s)) }

  def !(msg: MailBox#Message) =
    send(msg);

  def link(p: Process) =
    links = p::links;

  def spawn_link(body: => Unit) = {
    val p = new Process(body);
    p.link(this);
    p.start();
    p
  }

  //def self = this;

  def exit(reason: AnyRef): Unit = {
    exitReason = reason;
    interrupt()
  }

}