I have several threads that write data to the same buffer at the same time, but each one of them is writing to another range of indices in this buffer.
For example Thread1 is writing data only to indices 0-1000, Thread2 write only to indices 1001-2000, and Thread3 is writing only to indices 2001-3000.
Should I protect this buffer by using a lock method? Or is it a threads safe?
Thanks.
Editing:
It’s an int array:
int[] myArray = new int[3001];
CodePudding user response:
Yes, writing to a shared array from multiple threads in parallel, where each thread is writing to an exclusive part of the array, is thread-safe. This means that the array will not get corrupted during the write operation, and the written data will be preserved correctly (they will not get torn).
After the completion of the parallel writing operation it might be needed to add an explicit memory barrier, so that the data in the array are visible from the thread(s) that are going to read it. In general this is not needed, because the .NET infrastructure adds implicit memory barriers when various threading operations are started or completed. You can find a non-exhaustive list of these operations here: Memory barrier generators. I am mentioning this nuance because you have not provided any information about how you intend to read the array, after the writing phase has completed.