尝试使用线程来填充数组。程序似乎跳过了很多元素

时间:2018-12-08 12:17:32

标签: c# arrays multithreading

我正在尝试使用线程将数组的元素设置为等于其索引的平方根。我知道没有线程就可以轻松完成,但是我正在尝试学习线程。

运行此代码时,许多元素的默认值都不会更改为0。而且我不知道为什么。

class Program
{
    static double[] array = new double[100000000];

    static void Main()
    {
        int threadCount = 8;
        Thread[] threads = new Thread[threadCount];

        for (int i = 0; i < threadCount; i++)
        {
            threads[i] = new Thread(() => SquareRoot(i, threadCount));
            threads[i].Start();
        }
        for (int i = 0; i < threadCount; i++)
        {
            threads[i].Join();
        }
    }

    static void SquareRoot(int start, int incrementSize)
    {
        for (int i = start; i < array.Length; i += incrementSize)
        {
            array[i] = Math.Sqrt(i);
        }
    }
}

0 个答案:

没有答案