Are coroutines really thread safe? As far as I und...
# coroutines
g
Are coroutines really thread safe? As far as I understand this code can potentially print
0
. Because
i
can be modified from different threads and kotlin compiler doesn't mark it as
volatile
under the hood
j
Just curious, how did you implement
switchThread()
, and which dispatcher are you running
check()
in? Are you using
Unconfined
?
g
I don't use std lib here
Even if I used
Dispatcher
from std lib, I also could get this code run on different threads, because `Dispatcher`s have many threads under the hood
u
If you use e.g. withContext the compiler will take care of memory barriers. If you build your own context switching you have to take care of memory consistency yourself.
j
I don't think it should be a problem either way. The way suspension is implemented is via a state machine and a switch statement. So different parts of the code here are actually not even reading/writing the same local variable
i
. Each of the 3 sections of the
check
method are run during 3 different invocations of that method, each of which defining their own local
i
. The first section sets it to 0 and stores it in the continuation, the other 2 invocations initialize their own
i
from the continuation object.
e
with the JVM memory model, all reads and writes are ordered with respect to synchronization. so as long as
switchThread()
synchronizes,
i
is safe
u
@Joffrey the question is about the JVM memory model which does not guarantee visibility of changes across threads in general. Translated to a physical memory model this boils down to cache coherency. I.e each thread might run on a different core with is own hardware cache. And the changes of i++ might not have been synced to the cache of the core running the new thread when it tries to read the result
e
if
switchThread()
does not involve any synchronization or volatile operations, then indeed an older value of non-volatile
i
could be observed
g
@Joffrey I think you are wrong that there are multiple instances of
i
, because kotlin compiler optimizes code and create just 1 instance of
Continuation
where our
i
is stored
e
kotlinx.coroutines is always safe as it performs atomic operations at critical points
j
@Grigorii Yurkov if you read carefully what I wrote, I was referring to 3 different local variables
i
, but a single continuation to/from which the value of the local `i`s are read/written. So marking the local
i
volatile would be pointless. I might be wrong in concluding that solves the problem though (I just checked that the synthetic
Continuation
fields are not marked volatile either)
g
@ephemient how can I fix my
switchThread()
so it becomes thread safe? Because I don't see how it's possible. And I don't understand how std lib makes it thread safe
e
@Grigorii Yurkov honestly I think it's harder to make it non-thread-safe than it is to make it thread-safe. if you have an atomic run queue then it just works
g
@Joffrey Reread your comment again - yes I agree with you. Except in the part that there is no problem here
👍 1
e
e.g. if you are adding the paused continuation to a queue that another thread reads from to schedule and run, that must be synchronized for thread-safety, and that synchronization will force the reads and writes of
i
to be observed in the right order as well, even with its field in
Continuation
being non-volatile
g
@ephemient So you're trying to say, If I go to
Dispatcher
sources I will find synchronization there?
e
it's mostly hidden by
kotlinx.atomicfu
but yes
u
What are you trying to achieve in the first place? Would
yield
serve your purpose?
1
g
@uli I am trying to understand how std lib manages to be thread safe. The code is just an example to explain my point why I consider coroutines not thread safe by default
u
I see. Nobel purpose 🙂
e
https://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5
If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).
(regardless of whether x and y are volatile or not, if x occurs before y on a single thread, then they are ordered)
If an action x synchronizes-with a following action y, then we also have hb(x, y).
(is what defines happens-before edges across threads) so while non-volatile reads and writes between threads have no defined ordering relative to each other, once you add any synchronization then everything that was ordered before it, is also ordered before anything after it
anyway this is a lot of text to just say "they thought of that, Kotlin + kotlinx.coroutines makes it easy to write safe code". if you are writing your own non-kotlinx.coroutines coroutine framework then sure, you may need to worry about this…
g
@ephemient Yes, I understand that std lib developers are not stupid people who cannot write thread safe code. It's me who don't understand how it works. But you showed me the direction I need to learn more, thank you
e
@Grigorii Yurkov here's an demo of a coroutine dispatcher that is not thread safe. but note that it has obvious data races. kotlinx.coroutines doesn't https://pl.kotl.in/dEqx_fqfM
g
@ephemient Does changing queue with BlockingQueue make it safe?
e
with appropriate changes, yes
s
@Grigorii Yurkov Not sure how that is implemented under the hood, but your local
var i
is safe from race conditions. Coroutines guarantee that you can call suspend funs sequentially safely and not worry about race conditions and volatility.
g
@ephemient This makes reading/writing from
queue
safe, but I don't see why reading and writing from
i
becomes safe😞
e
@streetsofboston the suspend function translation of a "local"
var i
actually becomes part of the heap (in the generated
Continuation
). we are discussing how Kotlin makes that safe, because it's actually not the same safety as you have with a local variable
👍 1
1
@Grigorii Yurkov because writing to a synchronized queue forces
i
to be committed, and reading from a synchronized queue forces the updated
i
to be observed
we have
hb(i++, queue.put())
on one thread,
hb(queue.put(), queue.take())
across threads, and
hb(queue.take(), i)
on the new thread
g
I think I need to read when thread decides to put field from cache back to common memory or update cache from common memory
e
how the JVM implements that varies by platform, but the JLS does specify what implementations must provide
🙏 1