Access to an array of multiple threads

Let's say I have two arrays:

int[] array1 = new int[2000000];
int[] array2 = new int[2000000];

I put some values ​​in arrays and then want to add the contents of the array to array1 as follows:

for(int i = 0; i < 2000000; ++i) array1[i] += array2[i];

Now, let's say I want to make processing faster on a multiprocessor machine, so instead of just doing a loop as shown above, I create two threads. One of which I have the first 1,000,000 elements in the array, and the other I have the last 1,000,000 elements in the array. My main thread expects these two threads to notify you that they are finished, and then proceeds to use the values ​​from array1 for all kinds of important things. (Note that the two workflows cannot be completed and can be reused, but the main thread will not resume until they both notify it.)

So my question is: how can I be sure that the main thread will see the changes that the two worker threads made in the array? Can I expect this to happen, or do I need to go through some special procedure to make sure that worker threads erase their entries in the array and the main thread discards the values ​​of the cached arrays?

+5
source share
6 answers

You need a memory barrier to ensure that the worker thread will be written to the array, visible to the main thread in the expected order.

, , , . , , , . .

, Thread.MemoryBarrie r.

+2

.NET 4.0, :

Parallel.For(0, 2000000, i => { array1[i] += array2[i]; });

, :

  • ( for)
  • Parallel.For , , , .
+5

, , ? , , - , , , ?

- .

, , .

, , ~ ... , , , -.

+2

, , , (.. ), .

+1

, , - . .

0

All Articles