Skip to content

Instantly share code, notes, and snippets.

@vasmarfas
Created March 21, 2022 19:29
Show Gist options
  • Select an option

  • Save vasmarfas/a953a00231c033d7d7dcb4f5e5dc5c12 to your computer and use it in GitHub Desktop.

Select an option

Save vasmarfas/a953a00231c033d7d7dcb4f5e5dc5c12 to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.yield
import java.math.BigInteger
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
object Fibonacci {
suspend fun take(n: Int) {
yield()
withTimeout(3000) {
suspendCoroutine<BigInteger> { continuation ->
calculate(object : Callback {
override fun onSuccess(value: BigInteger) {
println("Calculated number from ${Thread.currentThread().name} - $value")
continuation.resume(value)
}
override fun onFailure(error: Throwable) {
println("error - ${error.message}")
continuation.resumeWithException(error)
}
}, n)
}
}
}
}
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.yield
import java.math.BigInteger
import kotlin.concurrent.thread
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
fun main() = runBlocking {
println("Program start: ${Thread.currentThread().name}")
launch {
take(1)
}
launch {
take(2)
}
launch {
take(70)
}
println("Program finished.")
}
fun calculate(callback: Callback, n: Int) {
thread {
println("Calculation start: ${Thread.currentThread().name}")
var first: Int = 0
var second: Int = 1
var i = 0
var sum: Int
do {
sum = first + second
first = second
second = sum
i++
} while (i <= n - 2)
callback.onSuccess(sum.toBigInteger())
}
}
suspend fun take(n: Int) {
// yield()
withTimeout(3000) {
suspendCoroutine<BigInteger> { continuation ->
calculate(object : Callback {
override fun onSuccess(value: BigInteger) {
println("Calculated number from ${Thread.currentThread().name} - $value")
continuation.resume(value)
}
override fun onFailure(error: Throwable) {
println("error - ${error.message}")
continuation.resumeWithException(error)
}
}, n)
}
}
}
interface Callback {
fun onSuccess(value: BigInteger)
fun onFailure(error: Throwable)
}
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment