invoke-fragmented.cc 1.34 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
#include <embb/algorithms/algorithms.h>
#include <cassert>

#include "algorithms/invoke/packages-snippet.h"

static int a = 0, b = 0, c = 0;

void WorkPackageA() {
  a++;
}

void WorkPackageB() {
  b++;
}

void WorkPackageC() {
  c++;
}

int* Partition(int* first, int* last) {
  int* pivot = last - 1;
  while (first != last) {
    while (*first < *pivot) {
      ++first;
      if (first == last) return first;
    }
    do {
      --last;
      if (first == last) return first;
    } while (*pivot < *last);
    std::swap(*first, *last);
    if(pivot == first) {
      pivot = last;
    } else if (pivot == last) {
      pivot = first;
    }
    ++first;
  }
  return first;
}

#include "algorithms/invoke/quick_sort-snippet.h"

#include "algorithms/invoke/parallel_quick_sort-snippet.h"

/**
 * Example using embb::algorithms::ParallelInvoke() to execute work packages in
 * parallel.
 */
void RunInvoke() {
  #include "algorithms/invoke/invocation-snippet.h"
  assert(a == 1);
  assert(b == 1);
  assert(c == 1);

  {
    int range[] = {2, 5, 3, 1, 4};
    QuickSort(range, range + 5);
    for (size_t i = 0; i < 5; i++) {
      assert(range[i] == static_cast<int>(i) + 1);
    }
  }
  {
    int range[] = {2, 5, 3, 1, 4};
    ParallelQuickSort(range, range + 5);
    for (size_t i = 0; i < 5; i++) {
      assert(range[i] == static_cast<int>(i) + 1);
    }
  }
}