Scoop API

scoop:scoop.concurrent:0.1.0

src/coroutine_workers.scoop

Selected production source · src/coroutine_workers.scoop

1package scoop.concurrent
3import scoop.platform.concurrent.ConditionVariable
4import scoop.platform.concurrent.Mutex
5import scoop.platform.concurrent.Thread
6import scoop.platform.concurrent.currentThreadId
8internal class CoroutineWorkers private constructor(
9 count: Int,
10 drivers: Array<CoroutineWorkerDriver>?
11) {
12 private val identity = CoroutineWorkerContext.nextIdentity()
13 private val records =
14 Array<CoroutineWorker>(count.toLong()) {
15 i -> CoroutineWorker(
16 i.toInt(),
17 when (drivers) {
18 case Some(val values) -> Some(values[i])
19 case None -> None
20 }
21 )
22 }
23 private val stopping = AtomicBoolean(false)
24 private val observers = AtomicInt(0)
25 private val assignment = AtomicInt(0)
26 private val lock = Mutex()
27 private val changed = ConditionVariable(lock)
28 private val listeners = TerminationListeners(lock)
29 private var live = 0
30 private var stopped = false
31 private var joining = false
32 private var joined = false
34 internal companion object {
35 internal fun create(count: Int, drivers: Array<CoroutineWorkerDriver>?): CoroutineWorkers {
36 if (count <= 0)
37 throw IllegalArgumentException(Some("worker count must be positive"))
38 val workers = CoroutineWorkers(count, drivers)
39 workers.start()
40 return workers
41 }
42 }
44 internal fun chooseWorker(): Int {
45 var current = assignment.load()
46 while (true) {
47 val next =
48 if (current + 1 == records.size.toInt())
49 0
50 else
51 current + 1
52 if (assignment.compareAndSet(current, next))
53 return current
54 current = assignment.load()
55 }
56 }
58 internal fun tryResume(affinity: AtomicInt, work: CoroutineWork): Boolean {
59 // With one worker there is no cross-worker handoff to eliminate.
60 if (records.size <= 1L)
61 return false
62 val current = CoroutineWorkerContext.current(identity)
63 if (current < 0)
64 return false
65 val record = records[current.toLong()]
66 if (!record.polling || record.executing || record.pollResumes == 32)
67 return false
68 record.pollResumes += 1
69 execute(record, affinity, work)
70 return true
71 }
73 internal fun submit(affinity: AtomicInt, work: CoroutineWork): Boolean {
74 val current = CoroutineWorkerContext.current(identity)
75 val target =
76 if (current >= 0)
77 current
78 else
79 affinity.load(MemoryOrder.Relaxed)
80 val record = records[target.toLong()]
81 val submission = CoroutineSubmission(affinity, work)
82 if (current >= 0) {
83 refill(record)
84 if (record.local.tryPut(submission)) {
85 notifyOne(target)
86 return true
87 }
88 }
89 if (!record.inbox.tryPut(submission))
90 return false
91 notifyOne(target)
92 return true
93 }
95 private fun notifyOne(preferred: Int) {
96 if (observers.load() == 0)
97 return
98 var index = preferred
99 var checked = 0L
100 while (checked < records.size) {
101 if (index == records.size.toInt())
102 index = 0
103 if (records[index.toLong()].notify())
104 return
105 index += 1
106 checked += 1L
107 }
108 }
110 private fun findWork(record: CoroutineWorker): CoroutineSubmission? {
111 record.localTurns += 1
112 if (record.localTurns == 32) {
113 record.localTurns = 0
114 when (record.inbox.take()) {
115 case Some(val work) -> return Some(work)
116 case None -> {}
117 }
118 when (steal(record, 1)) {
119 case Some(val work) -> return Some(work)
120 case None -> {}
121 }
122 }
123 when (record.local.take()) {
124 case Some(val work) -> return Some(work)
125 case None -> {}
126 }
127 refill(record)
128 when (record.local.take()) {
129 case Some(val work) -> return Some(work)
130 case None -> {}
131 }
132 // A paused thief can retain local slots; the inbox must remain runnable.
133 when (record.inbox.take()) {
134 case Some(val work) -> return Some(work)
135 case None -> {}
136 }
137 return steal(record, 128)
138 }
140 private fun refill(record: CoroutineWorker) {
141 if (record.local.refill(record.inbox) > 1)
142 notifyOne(record.index + 1)
143 }
145 private fun steal(record: CoroutineWorker, limit: Int): CoroutineSubmission? {
146 var checked = 0L
147 while (checked < records.size - 1L) {
148 if (record.victim == records.size.toInt())
149 record.victim = 0
150 val victim = record.victim
151 record.victim += 1
152 if (victim == record.index)
153 continue
154 checked += 1L
155 val source = records[victim.toLong()]
156 when (source.inbox.take()) {
157 case Some(val work) -> return Some(work)
158 case None -> {}
159 }
160 when (source.local.stealInto(record.local, limit)) {
161 case Some(val work) -> {
162 notifyOne(record.index + 1)
163 return Some(work)
164 }
165 case None -> {}
166 }
167 }
168 return None
169 }
171 private fun execute(record: CoroutineWorker, work: CoroutineSubmission) {
172 execute(record, work.affinity, work.work)
173 }
175 private fun execute(record: CoroutineWorker, affinity: AtomicInt, work: CoroutineWork) {
176 affinity.store(record.index, MemoryOrder.Relaxed)
177 record.executing = true
178 try {
179 work.run()
180 } finally {
181 record.executing = false
182 }
183 }
185 private fun poll(record: CoroutineWorker) {
186 record.pollResumes = 0
187 record.polling = true
188 try {
189 record.driver?.poll()
190 } finally {
191 record.polling = false
192 }
193 }
195 private fun drive(record: CoroutineWorker) {
196 var turns = 0
197 while (true) {
198 if (turns == 0) {
199 poll(record)
200 turns = 32
201 }
202 when (findWork(record)) {
203 case Some(val work) -> {
204 execute(record, work)
205 turns -= 1
206 continue
207 }
208 case None -> {}
209 }
210 if (stopping.load())
211 return
212 // Publish observation before scanning, so an enqueue either appears in this
213 // scan or changes the parking predicate before the worker can sleep.
214 observers.fetchAdd(1)
215 record.observe()
216 poll(record)
217 val work = findWork(record)
218 when (work) {
219 case Some(val work) -> {
220 val notified = record.stopObserving()
221 observers.fetchSub(1)
222 if (notified)
223 notifyOne(record.index + 1)
224 execute(record, work)
225 }
226 case None -> {
227 record.park(stopping)
228 record.stopObserving()
229 observers.fetchSub(1)
230 }
231 }
232 turns = 0
233 }
234 }
236 private fun start() {
237 try {
238 for (record in records) {
239 lock.withLock { live += 1 }
240 try {
241 val thread = Thread.start { run(record) }
242 lock.withLock { record.thread = Some(thread) }
243 } catch (error: Throwable) {
244 lock.withLock { live -= 1 }
245 throw error
246 }
247 }
248 } catch (error: Throwable) {
249 requestShutdown()
250 join()
251 throw error
252 }
253 }
255 private fun run(record: CoroutineWorker) {
256 try {
257 lock.withLock { record.id = Some(currentThreadId()) }
258 CoroutineWorkerContext.enter(identity, record.index)
259 try {
260 record.driver?.enter()
261 drive(record)
262 record.driver?.close()
263 } finally {
264 CoroutineWorkerContext.leave()
265 val notifications =
266 lock.withLock {
267 live -= 1;
268 finishIfEmpty()
269 }
270 notifications.deliver()
271 }
272 } catch (error: Throwable) {
273 error.printStackTrace()
274 exit(1)
275 }
276 }
278 internal val isTerminated: Boolean get() = lock.withLock { stopped }
280 internal fun onTermination(handler: () -> Unit): Disposable = listeners.subscribe(handler)
282 internal fun requestShutdown() {
283 for (record in records)
284 record.inbox.close()
285 stopping.store(true)
286 for (record in records)
287 record.notify()
288 val notifications = lock.withLock { finishIfEmpty() }
289 notifications.deliver()
290 }
292 private fun finishIfEmpty(): WaitNotifications {
293 val notifications = WaitNotifications()
294 if (stopping.load() && live == 0 && !stopped) {
295 stopped = true
296 listeners.finishLocked(notifications)
297 }
298 return notifications
299 }
301 internal val isCurrentWorker: Boolean get() {
302 val id = currentThreadId()
303 return lock.withLock {
304 for (record in records) {
305 when (record.id) {
306 case Some(val current) -> if (current == id)
307 return@withLock true
308 case None -> {}
309 }
310 }
311 false
312 }
313 }
315 internal fun join() {
316 if (isCurrentWorker)
317 throw IllegalStateException(Some("worker cannot wait for its own group"))
318 val perform =
319 lock.withLock {
320 if (!stopping.load())
321 throw IllegalStateException(Some("request shutdown before join"))
322 while (joining)
323 changed.await()
324 if (joined)
325 return@withLock false
326 joining = true
327 true
328 }
329 if (!perform)
330 return
331 try {
332 for (record in records) {
333 val thread = lock.withLock { record.thread }
334 when (thread) {
335 case Some(val thread) -> {
336 thread.join()
337 lock.withLock {
338 record.thread = None;
339 record.id = None
340 }
341 }
342 case None -> {}
343 }
344 }
345 lock.withLock { joined = true }
346 } finally {
347 lock.withLock {
348 joining = false;
349 changed.broadcast()
350 }
351 }
352 }