更新的问题更通用:为什么在这个例子中线程连接的行为有所不同?
我有以下代码。当你交换线程[i] .Join()的位置时,你会得到不同的输出。
static void ThreadedWorker(int startIndex, int endIndex)
{
Console.WriteLine("Working from results[ " + startIndex +"] to results["+endIndex+"]");
}
static void Main(string[] args)
{
int threadCount = System.Environment.ProcessorCount;
int calculationCount = 500; //the number of array elements we'd be iterating over if we were doing our work
int threadDataChunkSize = calculationCount/threadCount;
if (threadDataChunkSize < 1) threadDataChunkSize = 1; //just in case we have loads of threads
Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++)
{
threads[i] = new Thread(() => ThreadedWorker(threadDataChunkSize * i, threadDataChunkSize*(i+1)));
threads[i].Start();
//threads[i].Join(); //****Uncomment for correct behaviour****
}
for (int i = 0; i < threadCount; i++)
{
//threads[i].Join(); //****Uncomment for incorrect behaviour****
}
Console.WriteLine("breakhere");
}
当Join()
在第一循环中,创造连续的行为,你得到的输出
Working from results[ 0] to results[125]
Working from results[ 125] to results[250]
Working from results[ 250] to results[375]
Working from results[ 375] to results[500]
当Join()
是在第二循环中,建立一个平行的行为,你会得到不确定性的输出是这样的:
Working from results[ 375] to results[500]
Working from results[ 375] to results[500]
Working from results[ 500] to results[625]
Working from results[ 500] to results[625] (i is sometimes more than it should ever be!)
我怀疑lambda表达式以某种方式导致问题。希望这个改写也表明这不是一个界限的错误计算,或者其他滥用我的数组!
最初的问题不是通用的,而是使用startIndex和endIndex遍历一个正在工作的字节数组。我将ThreadedWorker
描述为“不工作”,因为它似乎有时会更新结果数组,有时不会。现在看来,它被称为,但起始索引和endindex被打破。
定义“不起作用”。 – 2011-06-16 16:28:51
我的输出数组分成8个块。前1/8似乎永远不会被填满,而较低的条纹有时会被填满,有时不会。这是全部或没有,所讨论的大块要么完全正确,要么完全错误。这使我相信'ThreadedBlend'永远不会被调用。 – 2011-06-16 17:48:38