package net.sergeych.synctools import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout /** * Platform-independent interface to thread wait/notify. Does nothing in JS/browser, * and uses appropriate mechanics on other platforms. */ @Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING") actual class WaitHandle { private val channel = Channel() actual fun await(milliseconds: Long): Boolean { return runBlocking { try { if( milliseconds > 0) { withTimeout(milliseconds) { channel.receive() true } } else { channel.receive() true } } catch(_: TimeoutCancellationException) { false } } } actual fun wakeUp() { runBlocking { channel.send(Unit) } } }