如何在parallel.for中捕获范围(0,MaxDegreeOfParallelism)中的线程ID

时间:2016-05-23 01:04:55

标签: c# multithreading parallel-processing

我想在范围(0到MaxDegreeOfParallelism)中为parallel.for中的每个传入线程分配和索引。我尝试过使用CurrentThread.ManagedThreadId和CurrentThread.Name,但它们不在给定的范围内,并认为它们有时会改变值(这是正确的吗?)。我现在使用的是ConcurrentStack,它的工作原理如下,但我认为这使得我的循环速度非常慢。知道如何解决这个问题吗?谢谢!

    int nCPU = 16;  //number of CORES
    ConcurrentStack<int> cs = new ConcurrentStack<int>();
    for (int i = 0; i < nCPU; i++) { cs.Push(i); }

    options.MaxDegreeOfParallelism = nCPU - 1;
    Parallel.For(0, 10000, options, tt =>
    {
        int threadIndex;
        cs.TryPop(out threadIndex); //assign an index to the incoming thread

        //..... do stuff with all my variables matrix1[threadIndex][i][j], matrix2.......//

        cs.Push(threadIndex);  //the thread leaves the previously assigned index 
    });

0 个答案:

没有答案