Skip to content

Instantly share code, notes, and snippets.

@enshahar
Created December 1, 2023 01:01
Show Gist options
  • Save enshahar/e0dc8f426da0b5374119a006529b8c98 to your computer and use it in GitHub Desktop.
Save enshahar/e0dc8f426da0b5374119a006529b8c98 to your computer and use it in GitHub Desktop.
1st implementation of launch (failed)
package learningtest
import kotlin.coroutines.*
private class MyCont<T>(override val context: CoroutineContext): Continuation<T> {
override fun resumeWith(result: Result<T>) {
println("Resume with: ${result}")
}
}
fun <T> CoroutineContext.launch(block: suspend CoroutineContext.()->T) =
block.startCoroutine(this, MyCont(this))
suspend fun test(msg: String, a:Int): Int {
println("$msg - 1")
delay(10)
println("$msg - 2")
delay(10)
println("$msg - 3")
return a * 2
}
suspend fun delay(t: Int) {
val start = System.currentTimeMillis()
var i = 0
while(true) {
val now = System.currentTimeMillis()
i++
if(i%10_000_000 == 0) println("busy waiting: ${"%,d".format(i)}")
if(now - start >= t) return
}
}
fun main() {
fun t() = java.time.LocalTime.now()
println("start ${t()}")
EmptyCoroutineContext.launch {
launch {
println("${test("1st", 30)}")
println("after 1st launch ${t()}")
}
launch {
println("${test("2nd", 30)}")
println("after 2nd launch ${t()}")
}
}
println("after launch ${t()}")
Thread.sleep(4000)
}
@enshahar
Copy link
Author

enshahar commented Dec 1, 2023

실행 결과:

start 11:00:02.266474
1st - 1
1st - 2
1st - 3
60
after 1st launch 11:00:02.300051600
Resume with: Success(kotlin.Unit)
2nd - 1
2nd - 2
2nd - 3
60
after 2nd launch 11:00:02.320648200
Resume with: Success(kotlin.Unit)
Resume with: Success(kotlin.Unit)
after launch 11:00:02.320648200

실패함!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment