在我看来,协程对于呼叫者和被呼叫者之间的本地交互非常有用,但是我很难理解它们将如何代替纤维。考虑下面的示例:我想控制并行度,以平衡我的cpu与磁盘I / O延迟,因此产生了多个生产者光纤和一个消费者光纤。
是否可以使用协程实现类似的功能?我们是否不需要某种调度程序就可以在异步进程之间进行切换?
using namespace boost;
void read_lines_fiber(const string& fname, fibers::buffered_channel<string>& chan) {
my_fiber_file f(fname, 'r'); // fiber friendly, suspends on IO read.
for (string s : f) {
chan.push(std::move(s));
}
}
void consume_lines(fibers::buffered_channel<string>& chan) {
string line;
while (true) {
channel_op_status st = chan.pop(line);
if (st == channel_op_status::closed)
break;
// ... use line....
}
}
void orchestrator(const vector<string>& filenames) {
fibers::buffered_channel<string> chan;
fibers::fiber consumer(&consume_lines, std::ref(chan));
std::vector<fibers::fiber> producer_handles;
// Launch all the producer fibers.
// We might want to limit number of concurrent fibers using fiber friendly semaphore.
for (const auto& s : filenames) {
producer_handles.emplace_back(&read_lines_fiber, std::ref(chan));
}
for (auto& fb : producer_handles) {
fb.join();
}
chan.close();
consumer.join();
}