Parallel中分区器Partitioner的简单使用

Partitioner.Create(1,10,4).GetDynamicPartitions()
为长度为10的序列创建分区,每个分区至多4个元素,分区方法及结果:Partitioner.Create(0, 10, 4).GetDynamicPartitions()
得到3个前闭后开区间: [0, 4)即{0, 1, 2, 3}, [4, 8)即{4, 5, 6, 7}, [8, 10)即{8, 9},  注意被枚举的数字均为数组下标
 
为长度为10的序列创建分区,至多4个分区,分区方法及结果: Partitioner.Create(0, 10, 3).GetDynamicPartitions()
得到4个前闭后开区间: [0,3)即{0, 1, 2}, [3, 6)即{3, 4, 5}, [6, 9)即{6, 7, 8}, [9, 10)即{9}, 注意被枚举的数字均为数组下标
 
定义分区个数 = 定义并发线程(笔者这样讲并不严格), 故定义方法如下:
private static void NewMethod<T>(IList<T> array, Int32 rangeCount) {
    var rangeSize = (Int32)Math.Ceiling(array.Count / (Double)rangeCount);
    var part = Partitioner.Create(0, array.Count, rangeSize);
    Parallel.ForEach(part, (range, state, rangeIndex) => {
        for (Int32 index = range.Item1; index < range.Item2; index++) {
            Console.WriteLine("[{0,2}] {1} {2}", Thread.CurrentThread.ManagedThreadId, rangeIndex, index);
        }
    });
}
 
对于分区个数定义为3, 可以看到线程ID 在1,3,4中切换, 线程[1]遍历了4个元素, 线程[3]遍历了4个元素, 线程[4]遍历了2个元素
 
对于分区个数定义为4, 可以看到线程ID 在1, 3, 4, 5中切换, 线程[1]遍历了3个元素, 线程[3]遍历了3个元素, 线程[4]遍历了3个元素, 线程5遍历了1个元素.
posted @ 2014-05-28 22:50  Jusfr  阅读(1522)  评论(0编辑  收藏  举报