'C++ changing vector in different thread

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

This is the code that start the threads:

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

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

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

this is the callback:

void callback(std::vector<uint64_t>  tmp){

    tmp[0] = 1;
    printf("inside callback");
    printArray(tmp);
}

and the output is:

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

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



Solution 1:[1]

If you wanted the callback to change the vector, you would have to pass it by pointer or reference.

Your callback code has made a copy of it instead.

Another option that can sometimes be more thread-safe is if you were to "move" the vector into the thread and then move it back out when the thread finishes. Like so:

#include <thread>
#include <future>
#include <vector>
#include <iostream>

std::vector<int> addtovec(std::vector<int> vec, int add) {
    for(auto &x: vec) {
        x += add;
    }
    return vec;
}

std::ostream& operator<<(std::ostream& os, const std::vector<int> &v) {
    os << '{';
    bool comma = false;
    for(const auto &x: v) {
        if(comma) os << ',';
        comma = true;
        os << x;
    }
    os << '}';
    return os;
}

int main() {
    std::vector<int> a{1,2,3,9,8,7};
    std::cout << "before: " << a << std::endl;

    auto future = std::async(addtovec, std::move(a), 5);
    std::cout << "after move: " << a << std::endl;
    a = future.get();

    std::cout << "after get: " << a << std::endl;
    return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1