2

I'm using posix threads and have a workerRoutine that in some cases has to wait for I/O.

//WorkerRoutine
while(true){
    if(NO CURRENT WORK){
      //sleep for I/O
      continue;
    }
    //Other cases....
}

My I/O function updates a statically-sized list. My problem is, when there's no current work for a worker, there's busy waiting. I'd like to have a sleep function in the worker function and a wake function in my readList (the I/O) function. What's the best way to do this in C?

Daniel
  • 317
  • 2
  • 9

1 Answers1

8

The closest pthreads equivalent of Java's wait and notify methods are available as functions accepting condition variables. Set up a condition variable, call pthread_cond_wait to wait for work, and pthread_cond_signal to announce that work is available.

Usage examples can be easily found on StackOverflow. and elsewhere.

If you are waiting for IO, another possibility is to use poll or equivalent to sleep until data arrives.

Community
  • 1
  • 1
user4815162342
  • 141,790
  • 18
  • 296
  • 355
  • 3
    Yes, this is very closely analogous to Java's `Object.wait()` and `Object.notify()`, including the relationship with a mutex (Java: monitor). There is also `pthread_cond_broadcast()` as an analog of Java's `Object.notifyAll()`. – John Bollinger Mar 16 '17 at 15:19