Scoop API

scoop:scoop.concurrent:0.1.0

src/termination_listeners.scoop

Selected production source · src/termination_listeners.scoop

1package scoop.concurrent
3import scoop.platform.concurrent.Mutex
5// Completion shares the owner's state lock; handlers are always invoked outside it.
6internal class TerminationListeners(private val lock: Mutex) {
7 private val entries = WaitQueue<TerminationListener>()
8 private var finished = false
10 internal fun subscribe(handler: () -> Unit): Disposable {
11 val entry = TerminationListener(this, handler)
12 val callNow =
13 lock.withLock {
14 if (finished)
15 return@withLock true
16 entry.link = Some(entries.append(entry))
17 false
18 }
19 if (callNow)
20 fire(entry)
21 return entry
22 }
24 // The caller commits its terminal state under this same lock.
25 internal fun finishLocked(notifications: WaitNotifications) {
26 finished = true
27 while (!entries.isEmpty) {
28 val entry = entries.takeFirst()!!
29 entry.link = None
30 notifications.add { fire(entry) }
31 }
32 }
34 internal fun remove(entry: TerminationListener) {
35 lock.withLock {
36 when (entry.link) {
37 case Some(val link) -> entries.remove(link)
38 case None -> {}
39 }
40 entry.link = None
41 entry.handler = None
42 }
43 }
45 private fun fire(entry: TerminationListener) {
46 val action =
47 lock.withLock {
48 val handler = entry.handler
49 entry.handler = None
50 handler
51 }
52 when (action) {
53 case Some(val handler) -> handler()
54 case None -> {}
55 }
56 }
59internal class TerminationListener(
60 private val owner: TerminationListeners,
61 handler: () -> Unit
62): Disposable {
63 internal var handler: (() -> Unit)? = Some(handler)
64 internal var link: WaitLink<TerminationListener>? = None
65 public override fun dispose() {
66 owner.remove(this)
67 }