我有以下读写器场景:
伪代码-请假定所有内容都是线程安全的:
// 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]);
}
}
}
}
我的问题:如何使读者摆脱无限循环?
我知道这是一个经典的问题,但是找不到处理它的资源。我所见过的所有内容都与不同类型的锁打交道,这不是我感兴趣的(如前所述-请假设所有内容都是线程安全的)。
使用共享标志,finished
。
[作者完成内容写入后,将设置标志finished = true
。
而不是让读取器永远与while (true)
循环,而是在设置标志while (!finished)
时终止。