使用并行进行时间排序.For仅对8个元素的子组进行排序

本文关键字:排序 元素 8个 仅对 时间 For 并行 | 更新日期: 2023-09-27 18:25:16

在C#中,我使用ParameterizedThreadStart生成了100个线程来对一个由100个元素组成的int数组进行排序,并且它具有适当的等待分辨率。现在,我使用Parallel.For(start,end,ParallelOptions,delegate=>{})尝试同样的方法,但它只对子组进行排序,并且它们的长度不超过核的数量。

   float[] sorted;
    Random r=new Random();
    int[] toBeSorted = new int[100];
    //creating random integers between 25 and 75 for an array
    for (int i = 0; i < 100; i++)
    {
        toBeSorted[i] = 25+(int)(r.Next(50));
    }
    //target array of sorted elements
    sorted = new float[101];
    //Telling that it can use 100 threads maximum
    ParallelOptions po = new ParallelOptions();
    po.MaxDegreeOfParallelism = 100;
    index = 0; // a static integer
    Object myLock = new Object();
    //time sorting. The lesser waiting elements are accumulated first. 
    Parallel.For(0, 100, po, i =>
        {
           Thread.Sleep(toBeSorted[i] * 100);//same resolution with Thread() version
           lock(myLock)
           {
               sorted[index] = toBeSorted[i];
               index++;
           }
        });
    Console.WriteLine();
    foreach (float s in sorted)
    {
        Console.Write("{0} ", s);
    }

输出:

29 44 45 48 50 54 44 65 59 45 73 32 59 34 46 28 45 71 36 69 36 46 40 72 74 70 62 30 39 55 30 29 32 64 45 66 38 66 47 57 45 33 62 48 41 47 55 53 28 52 28 63 46 32 31 29 61 41 55 31 54 48 37 38 51 59 68 40 31 37 40 37 71 52 66 45 25 57 57 70 59 74 70 54 72 69 0

问题1:我如何选择派生的最小线程数,或者是否有提示它应该派生指定的最大线程数?

问题2:如果元素的上界和下界已知,这种排序会比O(n)差吗?

不起作用的原因可能是parallel.fordata-parallelism工具而不是full-thread-parallelism工具吗?

谢谢。

编辑:添加锁(myLock){}并将索引放入正文中,使子组始终为8长度,这部分修复了排序。尽管如此,他们还是属于子群体。

编辑:使用ThreadPool.SetMinThreads(100100);max版本有效,但其他并行.for循环的性能下降,因此手动生成新线程似乎是更好的选择。

使用并行进行时间排序.For仅对8个元素的子组进行排序

Parallel.For使用底层ThreadPool来执行其工作,这就是为什么您没有看到它生成100个线程的原因。MaxDegreeOfParallelism只允许您将并发任务的数量限制为低于运行时"考虑"的任务数量,但不会规定实际并行执行的任务数量。

由于执行任务之间存在较大的睡眠间隙,静态index增量只能在没有锁定的情况下意外工作。