Hi,
I'm having difficulty comparing cilk_for with cilk_spawn. The following cilk_spawn code executes as I expect for command line arguments like 1000000 30
// Recursive Implementation of Map
// r_map.3.cpp
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <cilk/cilk.h>
const double pi = 3.14159265;
template<typename T>
class AddSin {
T* a;
T* b;
public:
AddSin(T* a_, T* b_) : a(a_), b(b_) {}
void operator()(int i) { a[i] = b[i] + std::sin(pi * (double) i / 180.) + std::cos(pi * (double) i / 180.) + std::tan(pi * (double) i / 180.); }
};
template <typename Func>
void r_map(int low, int high, int grain, Func f) {
if (high - low <= grain)
for (int i = low; i < high; i++)
f(i);
else {
int mid = low + (high - low) / 2;
cilk_spawn r_map(low, mid, grain, f);
}
}
int main(int argc, char** argv) {
if (argc != 3) {
std::cerr << "Incorrect number of arguments\n";
return 1;
}
int n = std::atoi(argv[1]);
int g = std::atoi(argv[2]);
int* a = new int[n];
int* b = new int[n];
for (int i = 0; i < n; i++) {
a[i] = b[i] = 1;
}
clock_t cs = clock();
r_map(0, n, g, AddSin<int>(a, b));
clock_t ce = clock();
std::cout << ce - cs / (double)CLOCKS_PER_SEC << std::endl;
delete [] a;
delete [] b;
}
If I replace the body of r_map with a simple cilk_for loop and set the number of workers environment variable to more than 1, this code generates segmentation faults once my command line arguments exceed 36000 30
// Recursive Implementation of Map
// r_map.2.cpp
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <cilk/cilk.h>
const double pi = 3.14159265;
template<typename T>
class AddSin {
T* a;
T* b;
public:
AddSin(T* a_, T* b_) : a(a_), b(b_) {}
void operator()(int i) { a[i] = b[i] + std::sin(pi * (double) i / 180.) + std::cos(pi * (double) i / 180.) + std::tan(pi * (double) i / 180.); }
};
template <typename Func>
void r_map(int low, int high, int grain, Func f) {
cilk_for (int i = low; i < high; i++)
f(i);
}
int main(int argc, char** argv) {
if (argc != 3) {
std::cerr << "Incorrect number of arguments\n";
return 1;
}
int n = std::atoi(argv[1]);
int g = std::atoi(argv[2]);
int* a = new int[n];
int* b = new int[n];
for (int i = 0; i < n; i++) {
a[i] = b[i] = 1;
}
clock_t cs = clock();
r_map(0, n, g, AddSin<int>(a, b));
clock_t ce = clock();
std::cout << ce - cs / (double)CLOCKS_PER_SEC << std::endl;
delete [] a;
delete [] b;
}
I'm compiling using GCC 4.9.0 20130520.
Can you explain why cilk_spawn works while cilk_for does not?