为什么我的多线程比单线程慢?

Kaz*_*mar 32 c# multithreading

我知道有几个人问了一个与此相似的问题,但我找不到任何能让我理解为什么它变慢的回答.

因此,我为自己对Visual Studio 2013中的线程对象的理解制作了一个小程序控制台程序.我的CPU是Intel Core i7,供应可以使用多个线程.

我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {

        static TimeSpan MTTime;
        static TimeSpan STTime;

        static void Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();


            Console.WriteLine(Environment.NewLine + "---------------Multi Process-------------" + Environment.NewLine);

            Thread th1 = new Thread(new ParameterizedThreadStart(Process));
            Thread th2 = new Thread(new ParameterizedThreadStart(Process));
            Thread th3 = new Thread(new ParameterizedThreadStart(Process));
            Thread th4 = new Thread(new ParameterizedThreadStart(Process));

            th1.Start("A");
            th2.Start("B");
            th3.Start("C");
            th4.Start("D");

            th1.Join();
            th2.Join();
            th3.Join();
            th4.Join();

            stopwatch.Stop();
            MTTime = stopwatch.Elapsed ;

            Console.WriteLine(Environment.NewLine + "---------------Single Process-------------" + Environment.NewLine);


            stopwatch.Reset();
            stopwatch.Start();

            Process("A");
            Process("B");
            Process("C");
            Process("D");

            stopwatch.Stop();
            STTime = stopwatch.Elapsed;

            Console.Write(Environment.NewLine + Environment.NewLine + "Multi  : "+ MTTime + Environment.NewLine + "Single : " + STTime);


            Console.ReadKey();
        }

        static void Process(object procName)
        {
            for (int i = 0; i < 100; i++)
            {
                Console.Write(procName);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

结果图片:

在此输入图像描述

我们可以清楚地看到,多踩踏过程是完全随机的,而单个踩踏过程只是一个接一个地按下,但我不认为这会对速度产生影响.

起初,我认为我的线程比运行程序所需的过程更大,但是在更换一个更大的进程之后,单步操作仍然是最快的.那么,我是否会错过多线程的概念?还是正常慢一点?

Cod*_*dor 71

请注意,Process写入控制台(并且基本上不执行任何其他操作),并且输出到控制台(此处充当一种共享资源)很慢并且需要与其他线程同步.

根据我的理解,您使用的并行化会产生巨大的开销但不会获得加速,因为线程显然主要是等待其他进程完成写入控制台的所有时间.

  • 究竟.对于OP:如果要对算法的单线程和多线程实现进行有效比较,则必须确保这些实现实际上可以完全独立地运行.特别是,它们不能使用任何共享资源,因为这会导致各个线程必须彼此等待. (29认同)

Sid*_*Sid 44

从官方控制台文档

使用这些流的I/O操作是同步的,这意味着多个线程可以读取或写入流.这意味着,如果对象表示控制台流,那么通常异步的方法(如TextReader.ReadLineAsync)将同步执行

这意味着控制台类处理线程同步,因此如果线程A和线程B试图写入控制台,控制台将处理它们,并且只有一个时间能够写入.它背后的处理逻辑是它需要更长时间的原因


更新
我建议你看看Parallel.ForEach