Multiple threads updating an array

I am trying to implement multithreading in my application, which does a lot of floating point calculations (neural network).

I wrote a function that does the necessary calculations and updates the array outside this function. My actual single-threaded code looks like this (simplified for a better understanding):

class MyClass { // this array after all calculations should contain // result of only one calculation, // that returned smallest value in one of array fields // (smallest neural network error) float[] bestResult; // runs calculations on all "sets of data" public void findBestResult(void) { foreach (something...) // data rows from database cached in one array { calculate(x[]); } } // calculates one "set of data" public void calculateAndUpdateResultIfBetter(float[] inputData) { if (bestResult[0] > calculatedData[0]) bestResult = calculatedData; // update only if condition is true } } 

I am a low level programmer, I don’t know how to use advanced (?) .NET streaming methods that use Synchronize, etc. I know how to create one additional thread for something and update some form controls using delegates.

I don’t know how to work with 2-8 threads doing the same and competing with each other.

Question 1 - can you help me? I don’t know where to start. Solved by Niko Draskovic

EDIT: Question 2 - does the lock () method lock my array for reading and writing?

+1
source share
1 answer

You use the lock statement to prevent multiple threads from running the same code at the same time. You will need a link to use as a lock identifier. Usually a simple object is created that is used only for locking:

 float[] bestResult; object sync = new Object(); 

Then around the code that accesses the array, you use lock :

 lock (sync) { if (bestResult[0] > calculatedData[0]) { bestResult = calculatedData; } } 

You might want each thread to first calculate the best value that it can see in the data for which it is responsible, and then combine these best values. If you run blocked code too often, you will make threads wait for each other, losing many reasons for running individual threads.

+5
source

Source: https://habr.com/ru/post/1441666/


All Articles