this is a beginner question i guess but i couldn't find the answer to this particular question:
i have a standard (c++) vector v of size 10 and type int.
is it safe to have a thread alter all the even positions (v.at(0) = x; v.at(2) = y; etc.) and another thread alter all the values for the odd positions (v.at(1) = a; v.at(3)=b;etc.) at the same time?
so, no changing of size, no push_back() etc. during the lifetime of these 2 threads.
if it is not safe, would the use of an array be a better way to do this?
thanks for your help.
Theoretically: No.
Practically: Yes (According how all well known STLs are implemented)
vector
does not provide any thread-safety guarantees, so technically the answer would be no.
In practice, you should be able to get away with it... until the day that someone (possibly you) makes a small change in one corner of the program and all hell breaks loose. I wouldn't feel comfortable doing this in any non-trivial program.
From MSDN: Thread Safety in the Standard C++ Library
For reads to the same object, the object is thread safe for reading:
For writes to the same object, the object is thread safe for writing from one thread when no readers on other threads
For reads to different objects of the same class, the object is thread safe for reading:
For writes to different objects of the same class, the object is thread safe for writing:
So from the above, Theorotically, NO, it won't be threadsafe.
It's machine-dependent. If you have a vector<char>
the processor might not be able to load v[i] and v[i+1] in separate words. You may have cache consistency problems.
Both the compiler and processor might re-order instructions, which can break your program even if the above doesn't apply. This is why C++0x has a memory model.
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