a question about cilk_for

a question about cilk_for

I ran into this problem while programming with cilk++. What I am trying to do is using cilk_for to copy one array (say array1) to another (array2). If I allocate array2 in the main function, then everything works fine (like in "copy_array"). However, if I allocate the space of array2 in the function where the cilk_for is used, I always get segmentation fault (see the function "generate_new_array"). Can anyone help find out where I am not using it correctly? Or does it have some limitations that I am not aware of? Thanks in advance!

Following is the code and output:

#include
#include
using namespace std;

int *generate_new_array(int *old_array, int array_size){
int *new_array = NULL;
new_array = new int [array_size];
cout << "before cilk_for in generate_new_array" << endl;
cilk_for(int i=0; i new_array[i] = old_array[i];
cout << "after cilk_for in generate_new_array" << endl;
return new_array;
}

void copy_array(int *new_array, int *old_array, int array_size){
cilk_for(int i=0; i new_array[i] = old_array[i];
cout << "after cilk_for in copy_array" << endl;
}

int cilk_main() {
int old_array[3] = {0, 1, 2};
int *new_array1 = new int[3];
copy_array(new_array1, old_array, 3);
delete [] new_array1;

int *new_array2 = generate_new_array(old_array, 3);
delete [] new_array2;
return 0;
}

//=== output ================================================
after cilk_for in copy_array
before cilk_for in generate_new_array
Segmentation fault

Thanks very much!
Liyun

4 Beiträge / 0 neu
Letzter Beitrag
Nähere Informationen zur Compiler-Optimierung finden Sie in unserem Optimierungshinweis.
Best Reply

Liyun,

I can reproduce the problem. It looks like this is a bug in the cilk++ compiler. Thanks for reporting it.

It looks like our compiler gets confused by the fact that the variable new_array is both used in the loop body and used as a return value. As a workaround until we fix the bug, you can say

int *new_array_tmp = new_array;

/* loop etc. */

return new_array_tmp; // instead of new_array

I apologize for this bug. The cause of the bug is probably the following. cilk_for() generates a separate function for the loop body, so that the body can be called in parallel from different worker threads. As part of this process, cilk_for() captures all variables used in the loop body and passes them as implicit arguments to the generated function. However, the return value normally lives in a special place (e.g., in the RAX register in 64 bit mode), and it looks like the capturing process is not working correctly in this case. Thanks again for catching it.

Thanks a lot, Matteo! Now I know when I should be more careful.

I just wrestled with this same bug for a couple hours. Should have checked here first, I guess :) Thanks for your help.

Melden Sie sich an, um einen Kommentar zu hinterlassen.