Tom Clabault Tom Clabault - 2 years ago 99
C Question

Can two threads write to different element of the same arrray?

Considering I'm about to multithread my code, I was wondering whether or not two threads could modify elements of the same array.

If I have

unsigned char array[4]
, can thread1 set
to 'A' and thread2 set
to 'B' at the same time without problems?

Answer Source

By definition, a race condition happens when 1 or more threads write data to the same location in memory while others read from it. Would multiple threads be writing to the same location in memory for a single array? The answer is no. Simply because the array is not changing. The program is simply calculating the position of the array by reading the position of the first element, and incrementing to the other elements. The writing happens only to one position at a time, and that's safe.

Actually I asked this question a very long time ago here, and based part of my PhD work on that. I fitted hundreds of curves (least-squares fitting) in parallel, while updating a single array that has the results by multiple threads.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download