Scoop API

scoop:scoop.concurrent:0.1.0

src/multi_thread_executor.scoop

Selected production source · src/multi_thread_executor.scoop

1package scoop.concurrent
3import scoop.platform.concurrent.ConditionVariable
4import scoop.platform.concurrent.Mutex
5import scoop.platform.concurrent.ThreadId
6import scoop.platform.concurrent.currentThreadId
8/** Runs coroutine work on fixed managed workers and blocking work on a separate pool. */
9public class MultiThreadExecutor internal constructor(
10 workerCount: Int,
11 private val blockingPool: BlockingTaskPool,
12 private val ownsBlockingPool: Boolean,
13 drivers: Array<CoroutineWorkerDriver>?
14): CoroutineExecutor, Closeable {
15 private val lock = Mutex()
16 private val changed = ConditionVariable(lock)
17 private val terminated = Channel<Unit>(0L)
18 private val terminationListeners = TerminationListeners(lock)
19 private val blockingThreads = ArrayList<ThreadId>()
20 private var phase = ExecutorPhase.Open
21 private var tasks = 0L
22 private var blockingWork = 0L
23 private var workersStopping = false
24 private val workers = CoroutineWorkers.create(workerCount, drivers)
26 init {
27 workers.onTermination { checkTermination() }
28 if (ownsBlockingPool)
29 blockingPool.invokeOnTermination { checkTermination() }
30 }
32 /** Whether shutdown has been requested and new root tasks are rejected. */
33 public val isShutdown: Boolean get() = lock.withLock { phase != ExecutorPhase.Open }
34 /** Whether tasks and owned workers have left their execution loops. */
35 public val isTerminated: Boolean get() = lock.withLock { phase == ExecutorPhase.Terminated }
37 /** Registers an ordinary termination notification without creating another coroutine. */
38 public fun invokeOnTermination(handler: () -> Unit): Disposable =
39 terminationListeners.subscribe(handler)
41 /** Registers a root while open, or a child of this executor's active parent while draining. */
42 public override fun registerTask(parent: ExecutorTask?): ExecutorTask =
43 lock.withLock {
44 if (phase == ExecutorPhase.Terminated)
45 throw ExecutorClosedException()
46 if (phase == ExecutorPhase.Draining) {
47 val admitted =
48 when (parent) {
49 case Some(val parent) -> parent is
50 MultiThreadTicket &&
51 parent.owner ===
52 this &&
53 parent.active
54 case None -> false
55 }
56 if (!admitted)
57 throw ExecutorClosedException()
58 }
59 val preferred =
60 when (parent) {
61 case Some(val parent) -> if (
62 parent is MultiThreadTicket && parent.owner === this
63 )
64 parent.affinity.load(MemoryOrder.Relaxed)
65 else
66 workers.chooseWorker()
67 case None -> workers.chooseWorker()
68 }
69 tasks += 1L
70 MultiThreadTicket(this, preferred)
71 }
73 /** Stops admission of new roots, preserving active tasks and their children. */
74 public fun requestShutdown() {
75 val stop =
76 lock.withLock {
77 if (phase == ExecutorPhase.Open)
78 phase = ExecutorPhase.Draining
79 shouldStopWorkers()
80 }
81 if (stop)
82 stopWorkers()
83 }
85 /** Waits for accepted work and owned workers; cancellation only ends this wait. */
86 public suspend fun awaitTermination() {
87 checkNotSelf()
88 terminated.receiveOrNone()
89 }
91 /** Waits for termination and joins owned threads after shutdown has been requested. */
92 public fun join() {
93 checkNotSelf()
94 lock.withLock {
95 if (phase == ExecutorPhase.Open)
96 throw IllegalStateException(Some("request executor shutdown before join"))
97 while (phase != ExecutorPhase.Terminated)
98 changed.await()
99 }
100 workers.join()
101 if (ownsBlockingPool)
102 blockingPool.join()
103 }
105 /** Requests shutdown and joins; cannot be called by work that must itself finish. */
106 public override fun close() {
107 checkNotSelf()
108 requestShutdown()
109 join()
110 }
112 internal fun dispatch(
113 ticket: MultiThreadTicket,
114 work: CoroutineWork,
115 resuming: Boolean = false
116 ) {
117 requireActive(ticket)
118 if (resuming && workers.tryResume(ticket.affinity, work))
119 return
120 if (!workers.submit(ticket.affinity, work))
121 throw IllegalStateException(Some("executor task is already complete"))
122 }
124 internal fun dispatchBlocking(ticket: MultiThreadTicket, work: BlockingWork) {
125 lock.withLock {
126 requireActive(ticket)
127 blockingWork += 1L
128 try {
129 blockingPool.submit(ExecutorBlockingWork(this, work))
130 }
131 catch (error: Throwable) {
132 blockingWork -= 1L
133 throw error
134 }
135 }
136 }
138 internal fun complete(ticket: MultiThreadTicket) {
139 val stop =
140 lock.withLock {
141 requireActive(ticket)
142 ticket.retire()
143 tasks -= 1L
144 shouldStopWorkers()
145 }
146 if (stop)
147 stopWorkers()
148 }
150 private fun requireActive(ticket: MultiThreadTicket) {
151 if (!ticket.active)
152 throw IllegalStateException(Some("executor task is already complete"))
153 }
155 internal fun runBlocking(work: BlockingWork) {
156 val id = currentThreadId()
157 lock.withLock { blockingThreads.add(id) }
158 try {
159 work.run()
160 }
161 finally {
162 lock.withLock {
163 var index = 0L
164 while (index < blockingThreads.size && blockingThreads[index] != id)
165 index += 1L
166 if (index == blockingThreads.size)
167 throw IllegalStateException(Some("blocking worker is not registered"))
168 blockingThreads.removeAt(index)
169 blockingWork -= 1L
170 }
171 checkTermination()
172 }
173 }
175 private fun shouldStopWorkers(): Boolean {
176 if (phase != ExecutorPhase.Draining || tasks != 0L || workersStopping)
177 return false
178 workersStopping = true
179 return true
180 }
182 private fun stopWorkers() {
183 workers.requestShutdown()
184 checkTermination()
185 }
187 private fun checkTermination() {
188 if (!workers.isTerminated)
189 return
190 if (ownsBlockingPool) {
191 blockingPool.requestShutdown()
192 if (!blockingPool.isTerminated)
193 return
194 }
195 val notifications = WaitNotifications()
196 val publish =
197 lock.withLock {
198 if (phase != ExecutorPhase.Draining || tasks != 0L || blockingWork != 0L)
199 return@withLock false
200 phase = ExecutorPhase.Terminated
201 terminationListeners.finishLocked(notifications)
202 changed.broadcast()
203 true
204 }
205 if (publish) {
206 notifications.add { terminated.close() }
207 notifications.deliver()
208 }
209 }
211 private fun checkNotSelf() {
212 val current = currentCoroutineExecutorOrNone()
213 when (current) {
214 case Some(val executor) -> if (executor === this)
215 throw IllegalStateException(Some("executor task cannot wait for its own executor"))
216 case None -> {}
217 }
218 if (workers.isCurrentWorker || (ownsBlockingPool && blockingPool.isCurrentWorker))
219 throw IllegalStateException(Some("worker cannot wait for its own executor"))
220 val id = currentThreadId()
221 val blocking =
222 lock.withLock {
223 for (worker in blockingThreads)
224 if (worker == id)
225 return@withLock true
226 false
227 }
228 if (blocking)
229 throw IllegalStateException(Some("blocking work cannot wait for its own executor"))
230 }
233private enum ExecutorPhase {
234 Open, Draining, Terminated
237private class ExecutorBlockingWork(
238 private val owner: MultiThreadExecutor,
239 private val work: BlockingWork
240): BlockingWork {
241 public override fun run() {
242 owner.runBlocking(work)
243 }