Reputation: 1498
As of now, Kotlin/Native is single-threaded. Therefore, the following code will become blocked by sleep
:
coroutineScope {
launch { plaform.posix._sleep(100000) }
launch { println("Hello") }
}
However, it has a novel concurrency mechanism called Workers. Yet, even with worker the main thread is going to be blocked by long-running posix call:
coroutineScope {
launch { Worker.start().execute(TransferMode.SAFE, { }, { plaform.posix._sleep(100000) }).consume{ } }
launch { println("Hello") }
}
Both of the snippets above will never print Hello
.
What is the correct way to perform a series of expensive blocking calls asynchronously?
Upvotes: 0
Views: 189
Reputation: 7670
There is a multithreaded version of kotlin coroutines for K/N, which lives on a separate branch currently: native-mt.
You could use Dispatchers.Default to offload tasks to the background thread
Upvotes: 4
Reputation: 1498
So, the problem is that I used the consume
method, which blocks the main thread.
Instead, you need to execute the worker, and then check manually whether it finished:
val job = Worker.start().execute(TransferMode.SAFE, { }) { plaform.posix._sleep(100000) }
...
if (job.state == FutureState.Computed)
job.result
Upvotes: 0