Reputation: 13931
Im trying to implement multi-threading in my application that makes a lot of float number calculations (neural network).
I wrote function that makes necessary calculations and updates array outside that function. My actual, single-thread code looks like this (simplified for 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
}
}
Im low level programmer, i don't know how to use advanced (?) .NET threading techniques, that use Synchronize etc. I know how to create one additional thread for something and update some controls on form by using delegates.
I have no idea how to work with 2-8 threads doing exactly same thing and competing with each other.
The question 1 is - can you help me with this? I don't know how to start. SOLVED BY Niko Drašković
EDIT: The question 2 is - will lock() method lock my array for read and write?
Upvotes: 1
Views: 2838
Reputation: 700322
You use the lock
statement to prevent different threads to run the same code at the same time. You would need a reference to use as an identifier for the lock. It's common to create a simple object that is used only for the 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 to have each thread first calculate the best value that it can see within the data that it is responsible for, and then combine those best values. If you run the locked code too often you will make the threads wait for each other, losing a lot of the reason for running separate threads in the first place.
Upvotes: 5