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?
OpenMP is a library for parallel programming in the SMP (symmetric multi-processors, or shared-memory processors) model. When programming with OpenMP, all threads share memory and data. OpenMP supports C, C++ and Fortran. The OpenMP functions are included in a header file called omp.
OpenMP is an implementation of multithreading, a method of parallelizing whereby a primary thread (a series of instructions executed consecutively) forks a specified number of sub-threads and the system divides a task among them.
The OpenMP programming model is SMP (symmetric multi-processors, or shared-memory processors): that means when programming with OpenMP all threads share memory and data. Parallel code with OpenMP marks, through a special directive, sections to be executed in parallel.
OpenMP introduces parallelism into your application by launching a set of threads that execute portions of your code concurrently. There are mechanisms, described below, that determine how many threads are launched and what portion of your code and what portion of your data each thread will use.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With