I have a question... situation not fully clear, bu...
# coroutines
o
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
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
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
@Olekss Don't use
Thread.sleep(...)
when you can use
delay(...)
instead.
o
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
you have reached threads limit in the thread pool
l
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
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
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
I know... I just somehow was assuming that infinite cycle produces "suspension" which it is not 🙂
l
You can add
yield()
in your loop and other coroutines will be able to run between iterations
o
yep, thanks