scoop:scoop.concurrent:0.1.0
src/coroutine_workers.scoop
Selected production source · src/coroutine_workers.scoop
1
package scoop.concurrent3
import scoop.platform.concurrent.ConditionVariable4
import scoop.platform.concurrent.Mutex5
import scoop.platform.concurrent.Thread6
import scoop.platform.concurrent.currentThreadId8
internal 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 -> None20
}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 = 030
private var stopped = false31
private var joining = false32
private var joined = false34
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 workers41
}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
050
else51
current + 152
if (assignment.compareAndSet(current, next))53
return current54
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 false62
val current = CoroutineWorkerContext.current(identity)63
if (current < 0)64
return false65
val record = records[current.toLong()]66
if (!record.polling || record.executing || record.pollResumes == 32)67
return false68
record.pollResumes += 169
execute(record, affinity, work)70
return true71
}73
internal fun submit(affinity: AtomicInt, work: CoroutineWork): Boolean {74
val current = CoroutineWorkerContext.current(identity)75
val target =76
if (current >= 0)77
current78
else79
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 true87
}88
}89
if (!record.inbox.tryPut(submission))90
return false91
notifyOne(target)92
return true93
}95
private fun notifyOne(preferred: Int) {96
if (observers.load() == 0)97
return98
var index = preferred99
var checked = 0L100
while (checked < records.size) {101
if (index == records.size.toInt())102
index = 0103
if (records[index.toLong()].notify())104
return105
index += 1106
checked += 1L107
}108
}110
private fun findWork(record: CoroutineWorker): CoroutineSubmission? {111
record.localTurns += 1112
if (record.localTurns == 32) {113
record.localTurns = 0114
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 = 0L147
while (checked < records.size - 1L) {148
if (record.victim == records.size.toInt())149
record.victim = 0150
val victim = record.victim151
record.victim += 1152
if (victim == record.index)153
continue154
checked += 1L155
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 None169
}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 = true178
try {179
work.run()180
} finally {181
record.executing = false182
}183
}185
private fun poll(record: CoroutineWorker) {186
record.pollResumes = 0187
record.polling = true188
try {189
record.driver?.poll()190
} finally {191
record.polling = false192
}193
}195
private fun drive(record: CoroutineWorker) {196
var turns = 0197
while (true) {198
if (turns == 0) {199
poll(record)200
turns = 32201
}202
when (findWork(record)) {203
case Some(val work) -> {204
execute(record, work)205
turns -= 1206
continue207
}208
case None -> {}209
}210
if (stopping.load())211
return212
// Publish observation before scanning, so an enqueue either appears in this213
// 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 = 0233
}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 error246
}247
}248
} catch (error: Throwable) {249
requestShutdown()250
join()251
throw error252
}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 = true296
listeners.finishLocked(notifications)297
}298
return notifications299
}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 true308
case None -> {}309
}310
}311
false312
}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 false326
joining = true327
true328
}329
if (!perform)330
return331
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 = None340
}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
}353
}