23

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

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

I have read that STL vector container is not thread-safe in the situation where multiple threads write to a single container, which would imply that I'd need to lock the vector before making any writes; however, I've also been told that the write operation above is somehow "atomic", and so there is no race condition above. Could someone clarify this?

1
  • Check for concurrent_vector which allows multiple reads, writes Commented Jun 9, 2013 at 8:46

2 Answers 2

35

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<int> 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.

Sign up to request clarification or add additional context in comments.

2 Comments

"not modifying the vector itself" -> "not using operations that could cause reallocation". But +1 anyway.
@larsmans Yes, that's a better wording that what I used. :) I'll change that. Thanks.
0

Multiple reads are safe but I would recommend to avoid multiple writes to the same container. But you can write to memory you manage on your own. The difference to a vector would be that you can be sure that the memory would not be changed or reallocated at the same time. Otherwise you can also use a semaphore but this would probably decrease the efficiency and if you use several it can even cause deadlocks if you don't work properly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.