c++c++11stlfalse-sharing

Can vector cause false sharing


I'm working with C++11 on a project and here is a function:

void task1(int* res) {
    *res = 1;
}

void task2(int* res) {
    *res = 2;
}

void func() {
    std::vector<int> res(2, 0); // {0, 0}
    std::thread t1(task1, &res[0]);
    std::thread t2(task2, &res[1]);
    t1.join();
    t2.join();
    return res[0] + res[1];
}

The function is just like that. You see there is a std::vector, which store all of the results of the threads.

My question is: can std::vector cause false sharing? If it can, is there any method to avoid false sharing while using std::vector to store the results of threads?


Solution

  • can std::vector cause false sharing?

    Containers aren't something that "cause" false sharing. It's writing to objects that may cause false sharing. Specifically, writing in one thread to an object that is in the same "cache line" as another object that is accessed in another thread causes false sharing.

    Elements of an array are adjacent in memory and hence adjacent small elements of an array are very likely in the same cache line. Vector is an array based data structure. The pattern of accessing the elements of the vector in your example are a good example of false sharing.

    is there any method to avoid false sharing while using std::vector to store the results of threads?

    Don't write into adjacent small elements of an array (or a vector) from multiple threads. Ways to avoid it are: