Norbi
01/04/2024, 9:49 PMcounter be volatile in the following example?
private var counter: Int = 1
private val contexts = (1..5).map { newSingleThreadContext("thread#$it") }
@Test
fun testCoroutine() {
runBlocking {
repeat(100) {
withContext(contexts[Random.nextInt(5)]) {
println(Thread.currentThread().name + "\t" + counter)
counter++
}
}
}
}
Thanks.Stanislav Kral
01/04/2024, 10:03 PM@Volatile is not necessary here since you're not running any coroutines in parallel here.ephemient
01/04/2024, 10:04 PM@Volatile, in essence every coroutine context switch is a sync pointNorbi
01/04/2024, 10:05 PMephemient
01/04/2024, 10:08 PMStanislav Kral
01/04/2024, 10:14 PMyield call at the end of the withContext 's block?ephemient
01/04/2024, 10:17 PM@Volatile would help you. you'd have to use atomicsNorbi
01/04/2024, 11:11 PMyield call" - ehhh, I left it there accidentally from a previous version - thanks for pointing that out, I have removed it for clarity.Norbi
01/04/2024, 11:26 PM@Volatile would help you. you'd have to use atomics" - I think it's not true, because only one thread is accessing counter at any given time, so there could be no race condition, so @Volatile is sufficient, there is no need for a higher level concurrency construct.
My question was: is @Volatile necessary, or the withContext() call does some magic in the background to synchronize the threads' memory like e.g. synchronized and ReentrantLock do in normal multi-threaded (non-coroutine) code.
The article you linked answered it, so @Volatile is really not necessary:
> Even though a coroutine in Kotlin can execute on multiple threads it is just like a thread from a standpoint of mutable state. No two actions in the same coroutine can be concurrent. And just like with threads you should avoid sharing your mutable state between coroutines or you’ll have to worry about synchronization yourself.
Thanks a lot 🙂🤓Daniel Pitts
01/05/2024, 2:53 AMjw
01/05/2024, 5:04 AMDaniel Pitts
01/05/2024, 5:05 AMephemient
01/05/2024, 8:37 AMNorbi
01/05/2024, 8:44 AMNorbi
01/05/2024, 8:47 AMDaniel Pitts
01/05/2024, 3:52 PMjw
01/05/2024, 3:52 PMDaniel Pitts
01/05/2024, 9:42 PMExecutors.newScheduledThreadPool to create the dispatcher worker, which uses various mechanisms to ensure correct concurrent behavior.Norbi
01/06/2024, 1:42 PM