summaryrefslogtreecommitdiff
path: root/src/library/scala/concurrent/Process.scala
blob: 39ce04484e3444bb53fc85d73049fe49ed1ceef2 (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
85
86
87
88
89
90
91
92
93
94
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2006, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |                                         **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

// $Id$


package scala.concurrent


import compat.Platform.UnsupportedOperationException

/** This object ...
 *
 *  @author  Erik Stenman
 *  @version 1.0, 01/10/2003
 */
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)

  /**
   *  @throws scala.compat.Platform.UnsupportedOperationException
   */
  def self: Process =
    if (Thread.currentThread().isInstanceOf[Process])
      Thread.currentThread().asInstanceOf[Process]
    else
      throw new UnsupportedOperationException("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()
  }

}