https://kotlinlang.org logo
#coroutines
Title
# coroutines
o

Olekss

02/12/2018, 12:28 PM
I have a question... situation not fully clear, but the observation is this: I invoke 3 "nodes" which each start 2 launch coroutine builders.... While each node is starting I do Thread.sleep(5000) on may thread (I run the stuff on main function) But what I observe is that 3rd node does not start until first one is destroyed (tus freeing some threads) As I told each node has 2 launchers where one is infinite cycle waiting on server connection (nonbloicking) incomming messages, but 2nd launch does .receive on channel So my version is that first 2 nodes somehow exhaust ForkJoin pool and my 3rd node does not start until I free something... can it be?
d

deviant

02/12/2018, 1:07 PM
if you use default dispatcher then it uses limited number of threads under the hood. cores-1 if i'm correct. so on 1 core system jobs may run synchronously one by one
k

kenkyee

02/12/2018, 2:02 PM
Use delay(). It's best to think of coroutines as cooperative threading IMHO...each coroutine sits on a thread but it has to give up control for others to run.
1
☝️ 1
l

louiscad

02/12/2018, 2:02 PM
@Olekss Don't use
Thread.sleep(...)
when you can use
delay(...)
instead.
o

Olekss

02/12/2018, 2:04 PM
I can't, as Thread.sleep is just one on the main thread, to see how the nodes behave... So yes, I take one of threads by myself, but I don't understand why 6 launches, where 3 of them are infinite cycle and 3 of them are channel.receive somehow blocks somewhere... But I will do some experiments...
d

deviant

02/12/2018, 2:04 PM
you have reached threads limit in the thread pool
l

louiscad

02/12/2018, 2:05 PM
Thread.sleep blocks a thread. When using it on a thread pool with a finite number of threads, you'll run out of threads very quickly, hence you should NEVER use
Thread.sleep(...)
when you can use
delay(...)
.
o

Olekss

02/12/2018, 2:06 PM
delay is suspending function
I am running stuff on main without runBlocking
so I simply simulate really one thread to be taken
but ok I added delay in my "infinite cycle" coroutine, it fixed stuff...
l

louiscad

02/12/2018, 2:06 PM
I can tell your CPU has 4 cores.
CommonPool
is CPU cores minus one, so 3 threads. If you block one in a coroutine, other coroutines that need a thread will use another thread in the pool... unless all are blocked...
o

Olekss

02/12/2018, 2:07 PM
I know... I just somehow was assuming that infinite cycle produces "suspension" which it is not 🙂
l

louiscad

02/12/2018, 2:08 PM
You can add
yield()
in your loop and other coroutines will be able to run between iterations
o

Olekss

02/12/2018, 2:11 PM
yep, thanks
3 Views