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


i new using threads , have read lot how data shared , protecting data. have not got grasp of when need use mutexes , locks protect data.

below description of problem working on. important thing note time critical need reduce overheads as possible.

i have 2 fixed size double arrays.

  • the first array provide data subsequent calculations. threads read values never modified. element may read @ time of threads.

  • the second array used store results of calculations
    performed threads. element of array ever updated 1 thread, , once when result value
    written it.

my questions then?

  1. do need use mutex in thread each time access data read-only array? if explain why?

  2. do need use mutex in thread when writes result array though thread ever writes element?

  3. should use atomic data types , there significant time on head if do?

  4. a lot of answers type of question seems - no, don't need mutex if variables aligned. array elements in example aligned, or there way ensure are?

the code implemented on 64bit linux. planning on using boost libraries multithreading.

thanks responses , comments have been mulling on , looking on web days, , once posted answer , clear explanations came in literally seconds. there "accepted answer", answers , comments equally helpful. again

under 2 conditions given, there's no need mutexes. remember every use of mutex (or synchronization construct) performance overhead. want avoid them as possible (without compromising correct code, of course).

  1. no. mutexes not needed since threads reading array.

  2. no. since each thread writes distinct memory location, no race condition possible.

  3. no. there's no need atomic access objects here. in fact, using atomic objects affect performance negatively prevents optimization possibilities such re-ordering operations.


Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -