【问题标题】:Multithreaded code executes by threadnumber-times slower using System.Threading and Visual Studio C# Express Hosting Process使用 System.Threading 和 Visual Studio C# Express 托管进程,多线程代码的执行速度慢了线程数倍
【发布时间】:2012-08-31 00:07:11
【问题描述】:

我有一个非常简单的程序来计算字符串中的字符。整数 threadnum 设置线程数,并将数据除以 threadnum 相应地分成块供每个线程处理。

每个线程递增共享字典中包含的值,构建字符直方图。

private Dictionary<UInt32, int> dict = new Dictionary<UInt32, int>();
  • 为了等待所有线程完成并继续主进程,我调用Thread.Join
  • 最初我为每个线程创建了一个本地字典,之后合并,但共享字典工作正常,没有锁定。
  • BuildDictionary 方法中没有锁定任何引用,但锁定字典不会显着影响线程执行时间。
  • 每个线程都是定时的,并比较结果字典。
  • 无论是单线程还是多线程,字典内容都是相同的 - 应该如此。
  • 每个线程需要一个由 threadnum 确定的分数来完成 - 应该如此。

问题:

总时间大概是threadnum的倍数,也就是说执行时间增加了?

(很遗憾,我目前无法运行 C# Profiler。此外,我更喜欢 C# 3 代码兼容性。)

其他人可能也在苦苦挣扎。可能是VS 2010 express edition vshost进程堆栈和调度线程顺序运行?

最近发布了另一个 MT 性能问题 here as "Visual Studio C# 2010 Express Debug running Faster than Release":

代码:

public int threadnum = 8;
Thread[] threads = new Thread[threadnum];
Stopwatch stpwtch = new Stopwatch();
stpwtch.Start();
for (var threadidx = 0; threadidx < threadnum; threadidx++)
{
    threads[threadidx] = new Thread(BuildDictionary);
    threads[threadidx].Start(threadidx);
    threads[threadidx].Join(); //Blocks the calling thread, till thread completion
}
WriteLine("Total - time: {0} msec", stpwtch.ElapsedMilliseconds);

你能帮忙吗?

更新:

由于 IDE 调试器的众多钩子,几乎线性的随着线程数增加而减速 的奇怪行为似乎是一个工件。

在开发人员环境之外运行该过程,我确实在 2 个逻辑/物理核心机器上获得了 30% 的速度提升。在调试期间,我已经处于 CPU 利用率的高端,因此我怀疑在开发过程中通过额外的空闲内核留有一些余地是明智的。

最初,我让每个线程在其自己的本地数据块上进行计算,该数据块被锁定并写回共享列表并在所有线程完成后聚合。

结论:

注意进程运行的环境。

【问题讨论】:

  • threads[threadidx].Join(); threadnum 次。
  • 但是如果我没记错的话,TPL 是在 C# 3 之后实现的?
  • @Lo Sauer 是的,TPL 是 C# 4 及更高版本

标签: c# multithreading visual-studio-2010 performance join


【解决方案1】:

只要集合未修改,字典就可以同时支持多个阅读器。来自MSDN

你说:

但是共享字典工作正常,没有锁定。

每个线程增加共享字典中包含的值

根据定义,您的程序已损坏,如果您在没有适当锁定的情况下更改字典中的数据,最终会出现错误。无需多言。

【讨论】:

  • 啊,我没再看了。我看到这一点,警报立即响起。即使他目前没有同时做任何事情,假设 OP 想要,这仍然适用
【解决方案2】:

罗姆看到了。

您的主线程应该在启动所有其他线程后加入 X 个其他线程。

否则它会等待第一个线程完成,然后启动并等待第二个线程。

for (var threadidx = 0; threadidx < threadnum; threadidx++)
{
    threads[threadidx] = new Thread(BuildDictionary);
    threads[threadidx].Start(threadidx);
}

for (var threadidx = 0; threadidx < threadnum; threadidx++)
{
    threads[threadidx].Join(); //Blocks the calling thread, till thread completion
}

【讨论】:

  • 好的。那么两个独立的循环?一个启动线程,另一个加入线程?
  • @LoSauer 你做了 2 个循环,1 个用于启动你的线程,1 个用于加入它们。编辑了我的答案,让你得到代码。
【解决方案3】:

我们可以暂时将 Tony the Lion 在他的回答中提到的字典同步问题放在一边,因为在您当前的实现中,您实际上并没有并行运行任何东西!

让我们看看你当前在循环中做了什么:

  • 开始一个线程。
  • 等待线程完成。
  • 开始下一个线程。

换句话说,你不应该在循环内调用Join。

相反,您应该像现在一样启动所有线程,但使用AutoResetEvent 等单一构造来确定所有线程何时完成。

查看示例程序:

class Program
{
    static EventWaitHandle _waitHandle = new AutoResetEvent(false);

    static void Main(string[] args)
    {
        int numThreads = 5;
        for (int i = 0; i < numThreads; i++)
        {
            new Thread(DoWork).Start(i);
        }
        for (int i = 0; i < numThreads; i++)
        {
            _waitHandle.WaitOne();
        }
        Console.WriteLine("All threads finished");
    }

    static void DoWork(object id)
    {
        Thread.Sleep(1000);
        Console.WriteLine(String.Format("Thread {0} completed", (int)id));
        _waitHandle.Set();
    }
}

如果您引用了可用的线程,也可以在第二个循环中调用Join。

完成此操作后,您可以并且应该担心字典同步问题。

【讨论】:

  • 能否提供一个快速的代码示例...非常感谢
  • 更新了我的答案以包含一个使用AutoResetEvent 进行单点的sn-p。
  • 为什么不在第二个循环中使用Join?如果两个线程快速连续调用Set,AutoResetEvent 可能会导致死锁。
【解决方案4】:

我完全同意 TonyTheLion 和其他人的观点,并且当您解决在错误位置加入的实际问题时,(无)锁定和更新共享字典仍然会有问题。我想给你一个快速的解决方法:只需将你的整数值包装到某个对象中:

代替:

Dictionary<uint, int> dict = new Dictionary<uint, int>();

使用:

class Entry { public int value; }
Dictionary<uint, Entry> dict = new Dictionary<uint, Entry>();

现在改为增加 Entry::value。这样一来,字典将不会注意到任何更改,并且不会锁定字典是安全的。

注意:这只有在你保证一个线程只使用它自己的一个条目时才有效。正如您所说的“字符直方图”,我刚刚注意到这不是真的。您必须在增量期间锁定每个条目,否则某些增量可能会丢失。尽管如此,与锁定整个字典相比,在入口层锁定会显着加快速度

【讨论】:

  • 谢谢。如前所述,我还使用本地字典进行了实现,将其写回到共享和锁定的字典列表中。性能是我主要关心的问题。等待线程的进程出了点问题...
  • 如果走这条路,在入口层使用Interlocked.Increment将无需在任何级别锁定。
【解决方案5】:

正如 Rotem 指出的那样,通过加入循环,您正在等待每个线程完成后再继续。

为什么会这样的提示可以在Thread.Join documentation on MSDN上找到

阻塞调用线程直到线程终止

所以在一个线程完成它的工作之前,你的循环不会继续。要启动所有线程然后等待它们完成,请将它们加入循环之外:

public int threadnum = 8;
Thread[] threads = new Thread[threadnum];
Stopwatch stpwtch = new Stopwatch();
stpwtch.Start();

// Start all the threads doing their work
for (var threadidx = 0; threadidx < threadnum; threadidx++) 
{
     threads[threadidx] = new Thread(BuildDictionary);
     threads[threadidx].Start(threadidx);
}
// Join to all the threads to wait for them to complete
for (var threadidx = 0; threadidx < threadnum; threadidx++) 
{
    threads[threadidx].Join();
}

System.Diagnostics.Debug.WriteLine("Total - time: {0} msec", stpwtch.ElapsedMilliseconds);

您确实需要发布您的 BuildDictionary 函数。多线程的操作很可能不会更快,线程开销实际上会增加执行时间。

【讨论】:

  • 与什么相比翻了一番?在你有时间*线程之前,不是时间*2?
【解决方案6】:

我不会使用一些共享的staticDictionary,如果每个线程都在本地副本上工作,那么一旦所有线程都发出完成信号,你就可以合并你的结果。

WaitHandle.WaitAll 避免了AutoResetEvent 上的任何死锁。

class Program
{
    static void Main()
    {
        char[] text = "Some String".ToCharArray();
        int numThreads = 5;

        // I leave the implementation of the next line to the OP.
        Partition[] partitions = PartitionWork(text, numThreads);

        completions = new WaitHandle[numThreads];
        results = IDictionary<char, int>[numThreads];

        for (int i = 0; i < numThreads; i++)
        {
            results[i] = new IDictionary<char, int>();
            completions[i] = new ManualResetEvent(false);
            new Thread(DoWork).Start(
                text,
                partitions[i].Start,
                partitions[i].End,
                results[i],
                completions[i]);
        }

        if (WaitHandle.WaitAll(completions, new TimeSpan(366, 0, 0, 0))
        {
            Console.WriteLine("All threads finished");
        }
        else
        {
            Console.WriteLine("Timed out after a year and a day");
        }

        // Merge the results
        IDictionary<char, int> result = results[0];
        for (int i = 1; i < numThreads - 1; i ++)
        {
            foreach(KeyValuePair<char, int> item in results[i])
            {
                if (result.ContainsKey(item.Key)
                {
                    result[item.Key] += item.Value;
                }
                else
                {
                   result.Add(item.Key, item.Value);
                }
            }
        }
    }

    static void BuildDictionary(
        char[] text, 
        int start, 
        int finish,
        IDictionary<char, int> result,
        WaitHandle completed)
    {
        for (int i = start; i <= finish; i++)
        {
            if (result.ContainsKey(text[i])
            {
                result[text[i]]++;
            }
            else
            {
               result.Add(text[i], 1);
            }
        }
        completed.Set();
    }
}

在此实现中,唯一共享的变量是text 的char[],并且始终是只读的。

您确实有最后合并字典的负担,但是对于避免任何并发问题,这是一个很小的代价。在更高版本的框架中,我会使用 TPL 和ConcurrentDictionary,可能还有Partitioner&lt;TSource&gt;。

【讨论】:

  • 比我的例子更好的实现,避免了@Tudor 提到的死锁。
猜你喜欢
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
  • 2016-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多