spierce7
09/22/2020, 1:32 AMZach Klippenstein (he/him) [MOD]
09/22/2020, 1:40 AMDefault
and IO
dispatchers share threads, but all the implementation details are internal I believe. In general, you shouldn’t need a dispatcher for this, just use a semaphore or worker pool or something to limit concurrency at a higher level.spierce7
09/22/2020, 1:44 AMprivate val scope = CoroutineScope(Executors.newSingleThreadExecutor(DaemonThreadFactory).asCoroutineDispatcher())
Zach Klippenstein (he/him) [MOD]
09/22/2020, 1:47 AMthen I’m creating my own threads thoughWhat do you mean? Using a semaphore/worker pool doesn’t create new threads.
spierce7
09/22/2020, 1:49 AMZach Klippenstein (he/him) [MOD]
09/22/2020, 1:50 AMspierce7
09/22/2020, 1:51 AMbezrukov
09/22/2020, 6:37 AMZach Klippenstein (he/him) [MOD]
09/22/2020, 11:15 AMsemaphore seems more annoying in this case than just having a single threaded coroutine, don't you think?
I'm not sure what you mean by "annoying". These are significantly different approaches with different tradeoffs. Threads are heavy and expensive, and one of the major benefits of using coroutines is that you don't need to create lots of them. The semaphore and worker approaches are much lighter weight since they can use the existing thread pools. They may or may not also make your code clearer, since they allow you to be more explicit about which parts of your code actually require synchronization.
Joffrey
10/06/2020, 3:18 PMonly one thread was accessing the coroutine at a time@spierce7 I’m not sure I understand. How could a single coroutine be executed by multiple threads at a given time? To make an analogy, your sentence sounds to me just like “only one core executing the thread at a time”. Do you mean that a group of coroutines would be confined to a single thread? (and thus you’re looking for a single-threaded dispatcher that shares his only thread with other dispatchers?)
spierce7
10/06/2020, 3:48 PMJoffrey
10/06/2020, 4:00 PMGlobalScope.launch(Dispatchers.Default) {
delay(100)
doSuspendingWork()
delay(200)
}
After each suspending call here, a different thread could take over the execution of the (single) coroutine, but there is never 2 threads executing any piece of this at the same time.
Is your issue about multiple coroutines instead (e.g. multiple nested launch
)? Or do you mean that you would like this coroutine to be always resumed on the same thread after each suspension?spierce7
10/07/2020, 1:10 PM