Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is < vector > threadsafe for read/write at different locations?

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.

like image 697
Ben the bear Avatar asked Jun 23 '11 13:06

Ben the bear


4 Answers

Theoretically: No.

Practically: Yes (According how all well known STLs are implemented)

like image 62
Mihran Hovsepyan Avatar answered Nov 12 '22 17:11

Mihran Hovsepyan


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.

like image 29
Jon Avatar answered Nov 12 '22 19:11

Jon


From MSDN: Thread Safety in the Standard C++ Library

For reads to the same object, the object is thread safe for reading:

  • From one thread at a time when no writers on other threads.
  • From many threads at a time when no writers on other threads.

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:

  • From one thread at a time.
  • From one thread at a time when no writers on other threads.
  • From many threads at a time.
  • From many threads at a time when no writers on other threads.

For writes to different objects of the same class, the object is thread safe for writing:

  • From one thread when no readers on other threads.
  • From many threads.

So from the above, Theorotically, NO, it won't be threadsafe.

like image 7
Alok Save Avatar answered Nov 12 '22 17:11

Alok Save


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.

like image 5
spraff Avatar answered Nov 12 '22 19:11

spraff