Taskflow:请求-取消与 性能分析

当向Executor(例如tf::Executor::run)提交任务流时,Executor返回一个tf::Future对象,该对象将保存执行结果。tf::Future是来自std::future的派生类。除了std::future的基本方法外,您还可以调用tf::Future::cancel来取消正在运行的任务流的执行。以下示例取消了任务流的提交,该任务流包含1000个任务,每个任务运行一秒钟。

cpp 复制代码
#include <taskflow/taskflow.hpp>
int main() {

    tf::Executor executor;
    tf::Taskflow taskflow;

    for(int i=0; i<1000; i++) {
    taskflow.emplace([](){ 
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::cout<<"Task\n";
    });
    }

    // submit the taskflow
    tf::Future<void> fu = executor.run(taskflow);

    // std::this_thread::sleep_for(std::chrono::seconds(2));
    // request to cancel the above submitted execution
    fu.cancel();

    // wait until the cancellation completes
    fu.get();

    taskflow.dump(std::cout);
}

当请求取消时,executor将停止调度任务流的其余Task。但已经运行的Task将继续完成。当所有这些运行Task完成后,取消被视为完成。要等待取消完成,您可以明确调用tf::Future::get, 注意, 一定要调用tf::Future::get等待executor执行完毕,否则可能会有未知的风险:

cpp 复制代码
tf::Executor executor;
{
  tf::Taskflow taskflow;
  
  for(int i=0; i<1000; i++) {
    taskflow.emplace([](){});
  }

  tf::Future fu = executor.run(taskflow);

  fu.cancel();  // there can still be task running after cancellation

} // destroying taskflow here can result in undefined behavior

tf::Future::cancel不保证立即取消。

性能分析

所有任务流程序都带有一个轻量级分析模块,以观察每个executor中的Worker活动。要启用分析器,需要将环境变量TF_ENABLE_PROFILER设置为存储分析结果的文件名。

cpp 复制代码
~$ TF_ENABLE_PROFILER=result.json ./my_taskflow
~$ cat result.json
[
{"executor":"0","data":[{"worker":12,"level":0,"data":[{"span":[72,117],"name":"12_0","type":"static"},{"span":[121,123],"name":"12_1","type":"static"},{"span":[123,125],"name":"12_2","type":"static"},{"span":[125,127],"name":"12_3","type":"static"}]}]}
]

然后将下面的json文本拷贝到:Taskflow Profiler, 进行可视化分析。

相关推荐
m0_55220082几秒前
《UE5_C++多人TPS完整教程》学习笔记61 ——《P62 武器开火特效(Fire Weapon Effects)》
c++·游戏·ue5
AA陈超3 分钟前
虚幻引擎5 GAS开发俯视角RPG游戏 P05-04 使用效果应用游戏标签
c++·游戏·ue5·游戏引擎·虚幻
老马啸西风31 分钟前
力扣 LC27. 移除元素 remove-element
算法·面试·github
数智顾问35 分钟前
中秋特别篇:使用QtOpenGL和着色器绘制星空与满月——从基础框架到光影渲染
算法
txwtech38 分钟前
第5篇 如何计算两个坐标点距离--opencv图像中的两个点
人工智能·算法·机器学习
CoovallyAIHub38 分钟前
YOLO26学界首评:四大革新点究竟有多强?
深度学习·算法·计算机视觉
用户9163574409538 分钟前
LeetCode热题100——11.盛最多水的容器
javascript·算法
Gorgous—l1 小时前
数据结构算法学习:LeetCode热题100-矩阵篇(矩阵置零、螺旋矩阵、旋转图像、搜索二维矩阵 II)
数据结构·学习·算法
2401_841495641 小时前
【计算机视觉】霍夫变换函数的参数调整
人工智能·python·算法·计算机视觉·霍夫变换·直线检测·调整策略
练习前端两年半1 小时前
🔍 你真的会二分查找吗?
前端·javascript·算法