forked from Kotlin/kotlinx.coroutines
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEventLoop.kt
51 lines (43 loc) · 1.69 KB
/
EventLoop.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines
internal actual abstract class EventLoopImplPlatform: EventLoop() {
protected abstract val thread: Thread
protected actual fun unpark() {
val thread = thread // atomic read
if (Thread.currentThread() !== thread)
unpark(thread)
}
protected actual fun reschedule(now: Long, delayedTask: EventLoopImplBase.DelayedTask) {
assert { this !== DefaultExecutor } // otherwise default execution was shutdown with tasks in it (cannot be)
DefaultExecutor.schedule(now, delayedTask)
}
}
internal class BlockingEventLoop(
override val thread: Thread
) : EventLoopImplBase()
internal actual fun createEventLoop(): EventLoop = BlockingEventLoop(Thread.currentThread())
internal actual inline fun platformAutoreleasePool(crossinline block: () -> Unit) = block()
/**
* Processes next event in the current thread's event loop.
*
* The result of this function is to be interpreted like this:
* * `<= 0` -- there are potentially more events for immediate processing;
* * `> 0` -- a number of nanoseconds to wait for the next scheduled event;
* * [Long.MAX_VALUE] -- no more events or no thread-local event loop.
*
* Sample usage of this function:
*
* ```
* while (waitingCondition) {
* val time = processNextEventInCurrentThread()
* LockSupport.parkNanos(time)
* }
* ```
*
* @suppress **This an internal API and should not be used from general code.**
*/
@InternalCoroutinesApi
public fun processNextEventInCurrentThread(): Long =
ThreadLocalEventLoop.currentOrNull()?.processNextEvent() ?: Long.MAX_VALUE