CPP26的exec模型你认为设计的如何?
作者:卡卷网发布时间:2025-03-05 22:04浏览数量:51次评论数量:0次
我觉得非常好。我第一时间能想到的有以下几个方面:
1、统一的异步模型,thread pool、GPU等这种资源调度以后都有了统一的调度接口,第三方库之间相互集成也变得更加方便。不仅仅是抽象出了scheduler/sender/receiver之类的接口,还封装了一些常用的异步算法,像when_all之类的,大大简化了异步代码的编写。
以前老有人问为什么STL中没有thread pool,其实只要就是因为C++还没有统一的异步模型,即使想要提供thread pool也没法确定需要提供什么样的api接口。现在不一样了,哪怕第三方的各种thread pool也可以轻松按照execution的模型来适配,stdexec里面就适配了好几个thread pool,包括tbb、asio等等:
链接:
https://github.com/NVIDIA/stdexec/tree/main/include/execpools2、协程和传统异步的高度统一,两种调用方式给你选择。协程方式主要是代码编写简单、可读性好,sender方式主要是可移植性更强,且性能更高。execution中的sender很容易就能支持co_await。
stdexec的文档中的这个例子:
我把它协程,就变成这样:
#include <stdexec/execution.hpp>
#include <exec/static_thread_pool.hpp>
#include <exec/task.hpp>
#include <print>
exec::task<std::tuple<int, int, int>> Work(auto& scheduler) {
auto fun = [](int i) { return i*i; };
auto work = stdexec::when_all(
stdexec::on(scheduler, stdexec::just(0) | stdexec::then(fun)),
stdexec::on(scheduler, stdexec::just(1) | stdexec::then(fun)),
stdexec::on(scheduler, stdexec::just(2) | stdexec::then(fun))
);
co_return co_await work;
}
int main()
{
exec::static_thread_pool pool(3);
auto scheduler = pool.get_scheduler();
auto work = Work(scheduler);
auto [tp] = stdexec::sync_wait(std::move(work)).value();
// expect(tp == std::tuple<int, int, int>(0, 1, 4));
}
3、应用structured concurrency思想,并将其推向新的高度。作为asio的粉丝,我觉得asio输得不冤。asio::co_spawn是不符合structured concurrency思想的:
youtube上有好几个关于Structured Concurrency思想的不错的视频,如果你只想看一个,我推荐这个:
https://www.youtube.com/watch?v=aPqMQ7SXSiw90年代C++凭借STL+上百种算法取得了非常强大的竞争力。C++26的execution就是并行并发编程时代的STL,在所有编程语言里面继续领先,甚至遥遥领先。
免责声明:本文由卡卷网编辑并发布,但不代表本站的观点和立场,只提供分享给大家。
- 上一篇:活了这么久,你悟出什么道理 ?
- 下一篇:华为的鸿蒙系统黄了吗?
相关推荐

你 发表评论:
欢迎