Using threads to optimize

Here is a C # code snippet that applies an operation to each row of the doubling matrix (suppose 200x200).

For (int i = 0; i < 200; i++)
{
   result = process(row[i]);
   DoSomething(result);
}

The process is a static method, I have a Corei5 processor and Windows XP, and I am using .Net Framework 3.5. To improve performance, I tried to process each line using a separate thread (using asynchronous delegates). So I rewrote the code as follows:

List<Func<double[], double>> myMethodList = new List<Func<double[], double>>();
List<IAsyncResult> myCookieList = new List<IAsyncResult>();
for (int i = 0; i < 200; i++)
{
   Func<double[], double> myMethod = process;
   IAsyncResult myCookie = myMethod.BeginInvoke(row[i], null, null);
   myMethodList.Add(myMethod);
   myCookieList.Add(myCookie);
}
for (int j = 0; j < 200; j++)
{
   result = myMethodList[j].EndInvoke(myCookieList[j]);
   DoSomething(result);
}

This code is called for 1000 matrices in a single pass. When I tested, suddenly I did not get any performance improvement! Therefore, this question arose for me: in what cases will multithreading be useful for increasing productivity, and is my code logical as well?

+3
6

. , .

, process() DoSomething() - ?

, .

, , Fx4 TPL ​​ , , .

+2

parallelism ( , ), BeginInvoke AsyncCallback - ThreadPool , .

. .

-, , , , .

+2

. ; 200 . , 201 . ; , " ", ( , , X2, ), , . 4 HT, 32 . 200, , .

, , MergeSort; , , . " " , " " . - , 1,25 " "; , , .

+1

, - - , EndInvoke. "" BeginInvoke, , , , . , EndInvoke , , , , - . , AsyncCallback, .

0

you don’t see much gain because you don’t parallelize the code, yes you do async, but it just means that your loop does not wait to calculate, to go to the next step. use Parallel.For instead of for loop and see if you see any gain in the multi-core box ...

0
source

If you intend to use async delegates, this will be the way to do this to make callbacks happen in the thread pool thread;

        internal static void Do()
    {
        AsyncCallback cb = Complete;

        List<double[]> row = CreateList();
        for (int i = 0; i < 200; i++)
        {
            Func<double[], double> myMethod = Process;
            myMethod.BeginInvoke(row[i], cb, null);
        }
    }
    static double Process (double[] vals)
    {
       // your implementation
        return randy.NextDouble();
    }
    static void Complete(IAsyncResult token)
    {

        Func<double[], double> callBack = (Func<double[], double>)((AsyncResult)token).AsyncDelegate;
        double res = callBack.EndInvoke(token);

        Console.WriteLine("complete res {0}", res);
        DoSomething(res);


    }
0
source

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


All Articles