Listings Wilkening HPX


Listing 1: „Hallo-Welt“ in HPX
#include <hpx/hpx.hpp>
#include <hpx/hpx_init.hpp>
#include <hpx/include/iostreams.hpp>

int hpx_main(boost::program_options::variables_map &vm)
{
    // Hierhin gehört der eigene Code
    hpx::cout << "Hallo HPX" << hpx::endl;
    return hpx::finalize();
}

int main(int argc, char *argv[])
{
    boost::options_description desc_commandline("Usage: HPX demo app [options]");
    return hpx::init(desc_commandline, argc, argv);
}

--------

Listing 2: Beispiel einer Funktion, die den String „42“ erzeugt
string make_string() 
{
    future<int> fut1 = async([](){ return 42; });
    future<string> fut2 = fut1.then(
      [](future<int> fut) 
      {
        return std::to_string(fut.get());    // Die Funktion "get" blockiert NICHT
      });
    return fut2.get();    // Gibt den String "42" zurück
}


});

--------

Listing 3: Hauptschleife einer Mandelbrot-Menge berechnen
hpx::parallel::for_loop(hpx::parallel::par, int(0), int(height), [&](int j) 
{
    const float y = j * dy + y1;
    for (int i = 0; i < width; ++i) {
      const float x = i * dx + x1;
      const int iter = pixel(x, y);
      const int index = i + j * width;
      picture[index] = t(iter);
    }
});

--------

Listing 4: Traversierung eines Binärbaums
template<typename Op> int traverse(Node* node, Op op)
{
    int left = 0, right = 0;
    define_task_block(
      par,    // <= Execution Policy
      [&](task_block<>& tb) 
      {
         if (node->left)
            tb.run([&] { left = traverse(node->left, op); });    // <= Neue Task
         if (node->right)
             tb.run([&] { right = traverse(node->right, op); });    // <= Neue Task
      });    // <= Join-Phase
    return left + op(n) + right;
}

--------

Listing 5: Verteilte Berechnung einer Fibonacci-Zahl
int fibonacci(int n)
{
    if (n<2) return n;

    hpx::naming::id_type here = hpx::find_here();

    fibonacci_action fib;
    hpx::future<int> n1 = hpx::async(fib, here, n-1);
    hpx::future<int> n2 = hpx::async(fib, here, n-2);

    return n1.get() + n2.get();
}
