Tom Clabault Tom Clabault - 2 years ago 107
C Question

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

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 (or write to it, too). Would multiple threads each modifying a different array element be writing to the same location in memory? The answer is no. Each array element has a region of memory reserved for it alone within the region attributed the overall array. Modifications of different elements therefore do not write to any of the same memory locations.

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