[英]C++ chain of tasks
我必須處理以下場景:我有5個任務(“A”,“B”,“C”,“D”,“E”),我想將它們並行化,但是就它們的依賴性而言。 他們必須按照這樣的順序執行:
A --> B --\
C ----------> E
D --------/
因此,當所有先前的完成並且必須在A之后執行“B”時執行“E”。這是我的問題。 有沒有准備好的解決方案(STL,Boost)? 或者我將基於std :: thread實現它?
查看TBB的Flow Graph或PPL 。
TBB鏈接中的示例大致顯示了您所繪制的內容。 您已經將您的問題抽象為任務。 首先無需深入到線程級別。
我認為您可以使用OpenMP section
指令執行此操作,您可以使用ICC,GCC和MSVC執行此操作。 OpenMP task
指令可能是更好的選擇,可以使用ICC和GCC,但不能使用任何版本的MSVC。
下面的代碼使用OpenMP sections
。 由於E在所有其他任務完成后運行,因此可以將其並行化,因此在下面的代碼中,在A, B, C, D
完成后A, B, C, D
所有線程都運行E
如果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();
}
您可以使用我從未使用的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所不具備的一些可能性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.