UNB/ CS/ David Bremner/ teaching/ cs3383/ examples/ spawn-race.cc
#include <iostream>
#include <cilk/cilk.h>
#include <cilk/cilk_api.h>

using namespace std;


void
sum(long i, long j, long &out) {

  if (i>j)
    return;
  
  if (i==j) {
    out++;
  } else {
  
    long m=(i+j)/2;

    cilk_spawn sum(i,m,out);

    sum(m+1,j, out);

    cilk_sync;
  }

}

int main(int argc, char** argv){

  long x = 0;

  const char *worker_param = "4";

  if (argc > 1)
    worker_param = argv[1];
  
  if (0!= __cilkrts_set_param("nworkers",worker_param))  {
      printf("Failed to set worker count\n");
      return 1;
    }

  sum(1,100000000, x);

  cout << x << endl;
}