Search code examples
multithreadinglanguage-agnosticreaderwriter

Let reader know that writer finished writing, and wait for reader to finish reading


I've got the following reader-writer scenario:

  1. A writer fires a reader.
  2. The reader spins infinitely, and starts reading from a shared buffer once it's written into.
  3. A writer starts writing to the shared buffer
  4. The writer waits for the reader to finish reading.
  5. program ends.

Pseudo code - please assume everything is thread safe:

// shared buffer
var buffer = new [3];

// 1. fire a thread, pass it a function named read
thread reader = new thread(read);

// 2. write some text to a shared buffer
var source = new [] {"line 1", "line 2", "line 3"};
for (int i = 0; ++i; i< source.length) {
   buffer[i] = source[i];
}

// 3. wait for reader to finish consuming the buffer
reader.join();


// 4. reader function
function void read() {
    while (true) {
        while (!buffer.empty()) {
           for (int i = 0; ++i; i< buffer.length) {
              print(buffer[i]);
           }
        }
    }
}

My question: How to make the reader get out of its infinite loop?

I know it's a classic problem, but couldn't find a resource that deals with it. All I've seen deals with different kinds of locks, which is not the thing I'm interested in (as said - please assume everything is thread safe).


Solution

  • Use a shared flag, finished.

    When the writer finishes writing its content, it sets the flag, finished = true.

    Instead of letting the reader loop forever with while (true), terminate when the flag is set, while (!finished).