加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么多线程在这里表现更差?

发布时间:2020-12-16 00:08:51 所属栏目:百科 来源:网络整理
导读:我通过bitarray设置枚举每秒都为false. 现在我想通过将它分成两个线程来加快速度……但是出于一些奇怪的原因,每个线程执行HALF工作量的时间需要64%的时间,我想知道为什么会这样? 这可能是由于某种CPU缓存效应?我该怎么做呢? 我以前用lambda表达式尝试了8
我通过bitarray设置枚举每秒都为false.

现在我想通过将它分成两个线程来加快速度……但是出于一些奇怪的原因,每个线程执行HALF工作量的时间需要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);
        }
    }

解决方法

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读