Is there a coroutine equivalent to to `pthread_con...
# coroutines
m
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
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
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
That could work. Or you could queue the suspend functions themselves, where the queued tasks are executed when enabled is toggled true.
s
Arrow also has a CountDownLatch, and a CyclicBarrier even if just for inspiration, the implementation is quite small but effective ☺️
🙏 1
👀 1
b
Enabled may be backed by StateFlow<Boolean>, in this case waiting for enabled will be just
enabled.first { it }
👍🏼 1
👍 2
j
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. ☝🏼