为什么多线程会在这里表现更差?

hl3*_*kel 3 c# multithreading

我通过bitarray设置枚举每秒都为false.

现在我想通过分割它分成两个线程.对于一些奇怪的原因,不过,每个线程做的时候加快这的工作量需要64%更多的时间,我不知道为什么?

这可能是由于某种CPU缓存效应?我该怎么做呢?

我以前用lambda表达式尝试了8个线程,但它总是大约1400毫秒,但是在单线程中我常常得到850毫秒.此外,当我让一个线程完成所有工作时,我花了830毫秒.我只是不明白,有人知道这里的原因吗?

码:

    class Program
    {
        static int count = 0x10000000;
        static int half = count / 2;
        static BitArray bitArray = new BitArray(count);

        static unsafe void Main(string[] args)
        {
            Stopwatch sw = Stopwatch.StartNew();

#if SINGLE
            for (int i = 0; i < bitArray.Count; i += 2)
                bitArray.Set(i, true);
#else
            Thread thread1 = new Thread(Thread1);
            Thread thread2 = new Thread(Thread2);
            thread1.Start();
            thread2.Start();
            thread1.Join();
            thread2.Join();
#endif
            sw.Stop();

            Console.WriteLine(sw.ElapsedMilliseconds);
            Console.ReadLine();
        }

        static void Thread1()
        {
            Stopwatch sw = Stopwatch.StartNew();
            for (int i = 0; i < half; i += 2)
                bitArray.Set(i, true);
            sw.Stop();
            Console.WriteLine("Thread1: {0}", sw.ElapsedMilliseconds);
        }

        static void Thread2()
        {
            Stopwatch sw = Stopwatch.StartNew();
            for (int i = half; i < count; i += 2)
                bitArray.Set(i, true);
            sw.Stop();
            Console.WriteLine("Thread2: {0}", sw.ElapsedMilliseconds);
        }
    }
Run Code Online (Sandbox Code Playgroud)

jod*_*ods 9

BitArray不是一个线程安全的类.你不应该这样使用它.事实上,除了正确性之外,这很可能是缓慢的原因.原因如下:

如果查看BitArray的源代码,它会包含一个int version字段,该字段会在每次操作时更新,特别是Set()您调用的字段.

这意味着每个线程不断更新相同的内存位置,这是一个巨大的性能杀手,因为所有内核在访问此位置时都必须进行通信和同步.在这种情况下,多线程解决方案的性能比单核解决方案更差,这是完全合理的.