我正在寻找 .NET TPL 数据流库的 C++ 模拟。
在 TPL 数据流中,您可以指定并行度和块的容量选项。如果块的输入队列的大小达到其容量,则暂停相应块的生产者的执行:
var buffer = new BufferBlock<int>(new DataflowBlockOptions() { BoundedCapacity = 10 });
var producer = new Task(() => {
for (int i = 0; i < 1000; i++) {
buffer.Post(i);
}
});
var fstAction = new TransformBlock<int, int>(async (i) => {
return i*i;
}, MaxDegreeOfParallelism = 4, BoundedCapacity = 10);
var sndAction = new ActionBlock<int>(async (i) => {
Thread.Sleep(5000);
Console.WriteLine(i);
}, MaxDegreeOfParallelism = 4, BoundedCapacity = 10);
buffer.LinkTo(fstAction, new DataflowLinkOptions() { PropagateCompletion = true });
fstAction.LinkTo(sndAction, new DataflowLinkOptions() { PropagateCompletion = true });
sndAction.Completition.Wait();
我需要 C++ 中的类似功能。TBB 似乎是一个不错的选择,但我找不到如何在function_node
/上指定容量buffer_node
。这是一个例子:
std::size_t exportConcurrency = 16;
std::size_t uploadConcurrency = 16;
flow::graph graph;
std::size_t count = 1000;
std::size_t idx = 0;
flow::source_node<std::vector<std::string>> producerNode(graph, [&count, &idx](auto& out) {
out = { "0"s };
return ++idx != count;
});
flow::function_node<std::vector<std::string>, std::string> exportNode(graph, exportConcurrency, [](auto& ids) {
return "0"s;
});
flow::function_node<std::string, std::string> uploadNode(graph, uploadConcurrency, [](auto& chunk) {
std::this_thread::sleep_for(5s);
return "0"s;
});
flow::make_edge(producerNode, exportNode);
flow::make_edge(exportNode, uploadNode);
graph.wait_for_all();