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?
do need use mutex in thread each time access data read-only array? if explain why?
do need use mutex in thread when writes result array though thread ever writes element?
should use atomic data types , there significant time on head if do?
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).
no. mutexes not needed since threads reading array.
no. since each thread writes distinct memory location, no race condition possible.
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
Post a Comment