C/C++ arrays with threads - do I need to use mutexes or locks?

The only time you need to use Locks is when data is modified on a shared resource. Eg if some threads where used to write data and some used to read data (in both cases from the same resource) then you only need a lock for when writing is done. This is to prevent whats known as "race".

There is good information of race on google for when you make programs that manipulate data on a shared resource.


  1. Do I really need to use a mutex in a thread each time I access the data from the read-only array? If so could you explain why?

No. Because the data is never modified, there cannot be synchronization problem.

  1. Do I need to use a mutex in a thread when it writes to the result array even though this will be the only thread that ever writes to this element?

Depends.

  1. If any other thread is going to read the element, you need synchronization.
  2. If any thread may modify the size of the vector, you need synchronization.

In any case, take care of not writing into adjacent memory locations by different threads a lot. That could destroy the performance. See "false sharing". Considering, you probably don't have a lot of cores and therefore not a lot of threads and you say write is done only once, this is probably not going to be a significant problem though.

  1. Should I use atomic data types and will there be any significant time over head if I do?

If you use locks (mutex), atomic variables are not necessary (and they do have overhead). If you need no synchronization, atomic variables are not necessary. If you need synchronization, then atomic variables can be used to avoid locks in some cases. In which cases can you use atomics instead of locks... is more complicated and beyond the scope of this question I think.

Given the description of your situation in the comments, it seems that no synchronization is required at all and therefore no atomics nor locks.

  1. ...Would my array elements in this example be aligned, or is there some way to ensure they are?

As pointed out by Arvid, you can request specific alignment using the alginas keyword which was introduced in c++11. Pre c++11, you may resort to compiler specific extensions: https://gcc.gnu.org/onlinedocs/gcc-5.1.0/gcc/Variable-Attributes.html


Under the two conditions given, there's no need for mutexes. Remember every use of a mutex (or any synchronization construct) is a performance overhead. So you want to avoid them as much as possible (without compromising correct code, of course).

  1. No. Mutexes are not needed since threads are only reading the array.

  2. No. Since each thread only writes to a distinct memory location, no race condition is possible.

  3. No. There's no need for atomic access to objects here. In fact, using atomic objects could affect the performance negatively as it prevents the optimization possibilities such as re-ordering operations.