Reputation: 99
Is there a minimal block size that multiple threads can write to in a contiguous block of memory that avoids race conditions or the losing of values?
For example, can 32 threads write to individual elements of this array without affecting the other values?
int array[32];
How about this?
bool array[32];
How about an object that stores simple true/false into a bit array?
I'm guessing there is some block write size or cache related functionality that would come into play that determines this. Is that correct? And is there anything standard/safe with regards to this size(platform defines, etc)?
Upvotes: 1
Views: 114
Reputation: 254461
Is there a minimal block size that multiple threads can write to in a contiguous block of memory that avoids race conditions or the losing of values?
No. A conflict (and potential data race) only occurs if two threads access the same memory location (that is, the same byte). Two threads accessing different objects won't conflict.
For example, can 32 threads write to individual elements of this array without affecting the other values?
Yes, each element has its own memory location, so two threads accessing different elements won't conflict.
How about this?
Yes; again, each bool
has its own location.
How about an object that stores simple true/false into a bit array?
No; that would pack multiple values into a larger element, and two threads accessing the same larger element would conflict.
I'm guessing there is some block write size or cache related functionality that would come into play that determines this.
There could be a performance impact (known as false sharing) when multiple threads access the same cache line; but the language guarantees that it won't affect the program's correctness as long as they don't access the same memory location.
Upvotes: 3
Reputation: 3379
There is no garuntee in standard. If you need exclusive access to element you may use std::atomic
.i.e. You may use like:
std::vector<std::atomic<int> > array;
Otherwise you are always free to use std::mutex
.
can 32 threads write to individual elements of this array without affecting the other values?
You are free to do this provided that one thread does interfare with other. i.e thread i
modifies the value of array[i]
ONLY.
Upvotes: 1