Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 815
Tom Clabault Avatar asked Aug 16 '17 18:08

Tom Clabault


People also ask

Can multiple threads read the same array?

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.

Can multiple threads write to the same file?

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.

What will happen if multiple threads accessing the same resource?

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.

Can two threads access the same data at the same time?

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.


1 Answers

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.

like image 182
The Quantum Physicist Avatar answered Nov 15 '22 17:11

The Quantum Physicist