If each thread is guaranteed to only read/write to a specific subset of the array can multiple threads work on the same (static) array without resorting to critical sections, etc?
EDIT - This is for the specific case of arrays of non-reference-counted types and record/packed-records thereof.
If yes, any caveats?
My gut feeling is yes but my gut can sometimes be an unreliable source of information.
Suppose that:
With these conditions, which I believe are met by your data structure and threading pattern, then all algorithms are thread-safe.
No, this could not be thread safe, in some situations.
I see at least two reasons.
1. It will depend on the static array content.
If you use some non-reference counted types (like double, integer, bytes, shortstring
), there won't be any issue in most case (at least if data is read/only).
But if you use some reference-counted types (like string, interface
, or a nested dynamic array), you'll have to take care of thread safety.
That is:
TMyType1: array[0..1] of integer; // thread-safe on reading
TMyType2: array[0..1] of string; // may be confusing
Additional note: if your string
is in fact shared among some sub-parts of the static array, you could have the reference count be confused. Unless you explicitly call UniqueString()
for each one (inside a critical section, I suspect). For an array of double
or integer
, you won't have this issue.
2. It will depend on the access concurrency
Read access should be thread safe, even for reference counted type, but concurrent write may be confusing. For a string
, you may have GPF issues in some random cases, especially on a multi-core CPU.
Some safe implementation may be:
Be aware that such issues may be a nightmare to debug, on client side: multi-thread concurrency issues may occur randomly, and are very difficult to track. The safer, the better, unless you have explicit and proven performance issues.
Additional note: For your specific case of static array of double, with sub-part of the array accessed by one thread only, it is thread-safe. But there is no absolute rule of thread safeness in all situations, even for a static array. As soon as you use some reference-counted types, or some pointers, you may have random issues.
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