OpenMP and STL vector

前端 未结 2 1817
庸人自扰
庸人自扰 2021-01-01 16:19

I\'ve got some code for which I\'d like to use OpenMP in the following way:

std::vector v(1000);
# pragma omp parallel for
for (int i = 0; i <          


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-01 16:39

    In this particular example, it will be safe.

    The reason is that you are not using operations that could cause a reallocation. (such as push_back()). You are only changing the contents of the individual elements.

    Note that you can just as legally do this:

    std::vector v(1000);
    int *ptr = &v[0];
    
    # pragma omp parallel for
    for (int i = 0; i < 1000; ++i) {
        ptr[i] = i;
    }
    

    It becomes not-thread-safe when you start calling methods like push_back(), pop_back(), insert(), etc... from multiple threads.

    I'll also add that this particular example isn't well-suited for parallelism since there's hardly any work to be done. But I suppose it's just a dumbed-down example for the purpose of asking this question.

提交回复
热议问题