开发者

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

开发者 https://www.devze.com 2023-03-15 03:00 出处:网络
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.

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 an开发者_如何学Cother 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.


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:

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


Theoretically: No.

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


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.


The scenario you describe will be tread-safe - you effectively manipulate individual elements of a fixed size array (since vector size will not change during those operations), so you don't need any additional synchronization in the first place unless you manipulate any element from more than one thread (which is not you case).

0

精彩评论

暂无评论...
验证码 换一张
取 消