I've got the following reader-writer scenario:
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).
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)
.