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