samedi 27 octobre 2018

C++ changing vector in different thread

I trying to change a vector in a different thread, but the value of the vector is not changed. I tried to search for an answer and I thought that using std::ref will fix the issue but it didn't work.

this is the code that start the threads:

std::vector<uint64_t> tmp(tmp_size);

printf("tmp size: %d\n", tmp_size);
printf("before change");
printArray(tmp);
std::thread threads[parallel_level];
for(int i = 0; i < parallel_level; i++){
    threads[i] = std::thread(binSearchMerge, std::ref(arr), std::ref(tmp), mid + 1, right, left, 0, left_size);
}

for(int i = 0; i < parallel_level; i++){
    threads[i].join();
}

printf("after join: ");
printArray(tmp);

this is the callback:

void binSearchMerge(std::vector<uint64_t>  arr, std::vector<uint64_t>  tmp, int searched_start_idx, int searched_end_idx, int merged_start_idx, int chunk_start, int chunk_end){

for(int i = chunk_start; i < chunk_end; i++){
    int arr_idx = merged_start_idx + chunk_start + i;
    bool found;
    int idx = binarySearch(arr, searched_start_idx, searched_end_idx, arr[arr_idx], &found);
    tmp[idx - searched_start_idx + i] = arr[arr_idx];
    printf("inside callback: ");
    printArray(tmp);
    }

}

and the output is:

tmp size: 2
before change 0 0
inside callback:  5800561435195166576 0
after join:  0 0

I was expecting that after the thread change the vector the values will be: inside callback: 5800561435195166576 0. isn't it passed by reference?

Aucun commentaire:

Enregistrer un commentaire