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

mbonnin

10/15/2023, 11:57 AM
Is there a coroutine equivalent to to
pthread_cond_wait
like there is
Mutex
for
pthread_mutex_t
? Have multiple coroutines suspend on a condition and resume all of them (one at a time) when it becomes true? Or am I thinking wrong?
j

Jeff Lockhart

10/15/2023, 1:03 PM
This comment from Roman might be relevant. Seems like the expected approach with coroutines is to just create new coroutines after awaiting completion of the first phase.
👀 1
m

mbonnin

10/15/2023, 3:05 PM
I don't really have a "phase", only an endless succession of state change. My problem can be reduced to this:
Copy code
var enabled: Boolean = false
  var lock = ReentrantLock()

  suspend fun backgroundTask() {
    while (true) {
      delay(Random.nextLong(1000))
      lock.withLock {
        enabled = !enabled
      }
    }
  }

  // Stuff that wants to interact with backgroundTask only when it's enabled
  // May be be called any number of times concurrently
  suspend fun anotherCoroutine() {
    lock.withLock {
      if (enabled) {
        doStuff()
      } else {
        // How I wait here?
      }
    }
  }
Maybe the naive implementation where it remembers the continuation could work, I'll give it a try
j

Jeff Lockhart

10/15/2023, 5:34 PM
That could work. Or you could queue the suspend functions themselves, where the queued tasks are executed when enabled is toggled true.
s

simon.vergauwen

10/15/2023, 5:47 PM
Arrow also has a CountDownLatch, and a CyclicBarrier even if just for inspiration, the implementation is quite small but effective ☺️
🙏 1
👀 1
b

bezrukov

10/15/2023, 7:04 PM
Enabled may be backed by StateFlow<Boolean>, in this case waiting for enabled will be just
enabled.first { it }
👍🏼 1
👍 2
j

Jeff Lockhart

10/15/2023, 7:35 PM
Cool, good to know, Simon. These synchronization primitives can be useful, especially when migrating existing Java algorithms to Kotlin. @Blake FYI, as we were discussing this recently. There are
CountDownLatch
and
CyclicBarrier
implementations in Kotlin, if you need. ☝🏼