|
| 1 | +package kotlinx.coroutines |
| 2 | + |
| 3 | +import kotlinx.atomicfu.* |
| 4 | +import kotlinx.coroutines.internal.* |
| 5 | +import kotlin.coroutines.* |
| 6 | +import kotlin.native.concurrent.ObsoleteWorkersApi |
| 7 | +import kotlin.native.concurrent.Worker |
| 8 | + |
| 9 | +@PublishedApi |
| 10 | +internal actual val DefaultDelay: Delay get() = DefaultDelayImpl |
| 11 | + |
| 12 | +@OptIn(ObsoleteWorkersApi::class) |
| 13 | +private object DefaultDelayImpl : EventLoopImplBase(), Runnable { |
| 14 | + init { |
| 15 | + incrementUseCount() // this event loop is never completed |
| 16 | + } |
| 17 | + |
| 18 | + private val _thread = atomic<Worker?>(null) |
| 19 | + |
| 20 | + /** Can only happen when tests close the default executor */ |
| 21 | + override fun reschedule(now: Long, delayedTask: DelayedTask) { |
| 22 | + throw IllegalStateException("Attempted to schedule $delayedTask at $now after shutdown") |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * All event loops are using DefaultDelay#invokeOnTimeout to avoid livelock on |
| 27 | + * ``` |
| 28 | + * runBlocking(eventLoop) { withTimeout { while(isActive) { ... } } } |
| 29 | + * ``` |
| 30 | + * |
| 31 | + * Livelock is possible only if `runBlocking` is called on internal default executed (which is used by default [delay]), |
| 32 | + * but it's not exposed as public API. |
| 33 | + */ |
| 34 | + override fun invokeOnTimeout(timeMillis: Long, block: Runnable, context: CoroutineContext): DisposableHandle = |
| 35 | + scheduleInvokeOnTimeout(timeMillis, block) |
| 36 | + |
| 37 | + override fun run() { |
| 38 | + val currentThread = Worker.current |
| 39 | + // Identity comparisons do not work for value classes, but comparing `null` with non-null should still work |
| 40 | + if (!_thread.compareAndSet(null, currentThread)) return // some other thread won the race to start the thread |
| 41 | + ThreadLocalEventLoop.setEventLoop(DelegatingUnconfinedEventLoop) |
| 42 | + try { |
| 43 | + while (true) { |
| 44 | + val parkNanos = processNextEvent() |
| 45 | + if (parkNanos == Long.MAX_VALUE) break // no more events |
| 46 | + if (parkNanos > 0) currentThread.park(parkNanos / 1000L, true) |
| 47 | + } |
| 48 | + } finally { |
| 49 | + _thread.value = null |
| 50 | + ThreadLocalEventLoop.resetEventLoop() |
| 51 | + // recheck if queues are empty after _thread reference was set to null (!!!) |
| 52 | + if (!delayedQueueIsEmpty) { |
| 53 | + /* recreate the thread, as there is still work to do, |
| 54 | + and `unpark` could have awoken the thread we're currently running on */ |
| 55 | + startThreadOrObtainSleepingThread() |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + override fun startThreadOrObtainSleepingThread(): Worker? { |
| 61 | + // Check if the thread is already running |
| 62 | + _thread.value?.let { return it } |
| 63 | + /* Now we know that at the moment of this call the thread was not initially running. |
| 64 | + This means that whatever thread is going to be running by the end of this function, |
| 65 | + it's going to notice the tasks it's supposed to run. |
| 66 | + We can return `null` unconditionally. */ |
| 67 | + scheduleBackgroundIoTask(this) |
| 68 | + return null |
| 69 | + } |
| 70 | + |
| 71 | + override fun toString(): String = "DefaultDelay" |
| 72 | +} |
| 73 | + |
| 74 | +private object DelegatingUnconfinedEventLoop: UnconfinedEventLoop { |
| 75 | + override val thisLoopsTaskCanAvoidYielding: Boolean |
| 76 | + get() = defaultDelayRunningUnconfinedLoop() |
| 77 | + |
| 78 | + override val isUnconfinedLoopActive: Boolean get() = false |
| 79 | + |
| 80 | + override fun runUnconfinedEventLoop(initialBlock: () -> Unit) { |
| 81 | + ioView.dispatch(ioView, Runnable { |
| 82 | + ThreadLocalEventLoop.unconfinedEventLoop.runUnconfinedEventLoop(initialBlock) |
| 83 | + }) |
| 84 | + } |
| 85 | + |
| 86 | + override fun dispatchUnconfined(task: DispatchedTask<*>) = |
| 87 | + defaultDelayRunningUnconfinedLoop() |
| 88 | + |
| 89 | + override fun tryUseAsEventLoop(): EventLoop? = null |
| 90 | +} |
| 91 | + |
| 92 | +private fun defaultDelayRunningUnconfinedLoop(): Nothing { |
| 93 | + throw UnsupportedOperationException( |
| 94 | + "This method can only be called from the thread where an unconfined event loop is running, " + |
| 95 | + "but no tasks can run on this thread." |
| 96 | + ) |
| 97 | +} |
| 98 | + |
| 99 | +/** A view separate from [Dispatchers.IO]. |
| 100 | + * [Int.MAX_VALUE] instead of `1` to avoid needlessly using the [LimitedDispatcher] machinery. */ |
| 101 | +private val ioView = Dispatchers.IO.limitedParallelism(Int.MAX_VALUE) |
0 commit comments