【问题标题】:Task parallelization and data synchronization in a pipeline管道中的任务并行化和数据同步
【发布时间】:2016-02-24 15:33:21
【问题描述】:

我有 5 个独立的组件 A、B、C、D、E,其中 A 和 B 正在生成数据,C 和 D 正在处理来自 A 和 B 的数据,E 将可视化来自 C 和 D 的结果。

实现此管道最直接的方法是将它们全部放在一个线程中:

while (keep_running)
    A->B->C->D->E

但是 C 和 D 可以并行以提高效率。组件 A 和 B 可能也是如此。

while (keep_running)
    {A && B could be in parallel} -> {C && D in parallel} -> E

我想知道实现这一点的有效方法是什么。

谢谢!

更新:抱歉不清楚。

让我以伪代码的方式提出我的问题。

// keep_running is just a bool, could be updated to terminate the loop 
while (keep_running) 
      run A; // produce data
      run B; // produce data 
      run C; // processing data from A and B 
      run D; // processing data from A and B
      run E; // visualize results from B and C

while (keep_running)
      create_thread ta to run A;
      create thread tb to run B;
      ta.run();
      tb.run();
      join ta and tb;
      create thread tc to C;
      create thread td for D;
      tc.run();
      td.run();
      join tc and td;
      run E; 
      destroy ta,tb,tc,td;

// I think above implementation is not efficient, because create and destroy threads every time
// I wonder if there're some efficient implementation like:
create thread ta,tb,tc,td;
while (keep_running)
      ta.run_once();
      tb.run_once();
      wait ta and tb; // A and B finish a round and go to sleep.
      tc.run_once();
      td.run_once();
      wait tc and td;
      run E;
destroy ta, tb, tc, td

// Or other more efficient way ?

我在线程方面没有太多经验,对于不清楚的问题表示歉意,希望有人能给我一些提示,我可以解决这个问题。

谢谢。

【问题讨论】:

  • 请在 C 或 C++ 中选择 一个
  • @MikeCAT 为什么?我可以接受 C 或 C++ 的答案。
  • 只有我一个人,还是这个问题在没有上下文的情况下完全不清楚?
  • @Jeff 这里的箭头只表示执行顺序,不表示数据流向。

标签: c++ c multithreading


【解决方案1】:

为 A 和 B 创建两个线程,在它们后面放置一个屏障,这样你就不会遇到冲突。 为C&D创建两个线程,处理,放置屏障 完成 E.L

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多