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 array[0]
and array[1]
to 'A' and thread2 set array[2]
and array[3]
to 'B' at the same time without problems?
Many threads can read a mutable instance of an array simultaneously without an issue but it is unsafe to let one thread modify the array while another is reading it.
Different threads should never try to write to the same FITS file. A single process may open the same FITS file with READONLY access multiple times, and thus create multiple 'fitsfile*' pointers to that same file within CFITSIO.
Multiple threads accessing shared data simultaneously may lead to a timing dependent error known as data race condition. Data races may be hidden in the code without interfering or harming the program execution until the moment when threads are scheduled in a scenario (the condition) that break the program execution.
A data race is a state, in which at least two threads access shared data at the same time, and at least one of the threads is a writer. A critical section is a section of the code, which not more than one thread should access at any point in time.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With