C ++任务链

时间:2013-06-17 07:01:05

标签: c++ multithreading boost c++11

我必须处理以下场景:我有5个任务(“A”,“B”,“C”,“D”,“E”),我想将它们并行化,但是关于它们的dependiences。它们必须按照这样的顺序执行:

A --> B --\
C ----------> E
D --------/

因此,当所有先前的完成后执行“E”并且必须在A之后执行“B”。这是我的问题。有没有准备好的解决方案(STL,Boost)?或者我将基于std :: thread?

实现它

3 个答案:

答案 0 :(得分:11)

结帐TBB's Flow GraphPPL

TBB链接中的示例大致显示了您所绘制的内容。您已经将您的问题抽象为任务。无需首先进入线程级别。

答案 1 :(得分:2)

我认为您可以使用OpenMP section指令执行此操作,您可以使用ICC,GCC和MSVC执行此操作。 OpenMP task指令可能是更好的选择,可以使用ICC和GCC完成,但不能使用任何版本的MSVC。

以下代码使用OpenMP sections。由于E在所有其他任务完成后运行,因此可以将其并行化,因此在E完成后,所有线程都会运行以下代码A, B, C, D。如果E正在迭代循环,那么您可以通过这种方式并行化循环。我不确定这是你想要的,但很容易让它在一个线程中运行,就好像你想要的那样。

#include <stdio.h>
#include <omp.h>

void A() { printf("A\n"); }
void B() { printf("B\n"); }
void C() { printf("C\n"); }
void D() { printf("D\n"); }
void E() {
  printf("E: %d\n", omp_get_thread_num());
  #pragma omp for
  for(int i=0; i<10; i++) {
     //do something as a function of i
  }
}

void foo() {
#pragma omp parallel // starts a new team
 {  
   #pragma omp sections // divides the team into sections
   { 
     { A();  B(); }
     #pragma omp section
     { C(); }
     #pragma omp section
     { D(); }
   }
   E();
 }
}

int main() {
    foo();
}   

答案 2 :(得分:1)

你可以使用我从未使用的std :: thread,但看起来非常简单。

以下是cppreference.com上的简单程序示例:

#include <iostream>
#include <thread>
#include <chrono>

void foo()
{
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

void bar()
{
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main()
{
    std::cout << "starting first helper...\n";
    std::thread helper1(foo);

    std::cout << "starting second helper...\n";
    std::thread helper2(bar);

    std::cout << "waiting for helpers to finish...\n";
    helper1.join();
    helper2.join();

    std::cout << "done!\n";
}

您可以使用join()函数等待线程完成。 例如,您创建一个将执行任务A的新线程。然后在创建将执行任务B的新线程之前等待它完成。

您应该使用g ++ -std = c ++ 0x -pthread main.cpp

进行编译

或者你可以搜索MPI和OpenMP,它们可以提供某种可能性std :: thread不能。

相关问题