更新的問題更通用:爲什麼在這個例子中線程連接的行爲有所不同?
我有以下代碼。當你交換線程[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