C ++ task chain

I need to process the following scenerio: I have 5 tasks ("A", "B", "C", "D", "E"), I would like to parallelize them, but with regard to their dependiences. They must be performed in this order:

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

So, ā€œEā€ is executed when all previous ones are completed, and ā€œAā€ should be executed after A. And here is my question. Are there any ready-made solutions (STL, Boost)? Or will I have to implement it based on std :: thread?

+6
source share
3 answers
+11
source

I think you can do this with the OpenMP section directive, which you can do with ICC, GCC and MSVC. The OpenMP task directive is probably the best choice and can be done with ICC and GCC, but not with any version of MSVC.

The code below uses OpenMP sections . Since E starts after all other tasks are completed, it can also be parallelized, so in the following E code, all threads are executed after A, B, C, D . If E iterates over a loop, you can parallelize the loop this way. I'm not sure what you want, but it's easy to get it working on a single thread, as if you wanted to.

 #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
source

You can use std :: thread, which I have never used but seems pretty simple.

Here is an example of a simple program found at 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"; } 

You can use the join () function to wait for the stream to finish. For example, you create a new thread that will complete task A. Then you wait for it to complete before creating a new thread that will complete task B.

You should compile with g ++ -std = C ++ 0x -pthread main.cpp

Alternatively, you can look for MPI and OpenMP, which may provide some of the features of std :: thread can not.

+1
source

Source: https://habr.com/ru/post/947430/


All Articles