【问题标题】:Why time is increasing in my Multithreading example as thread count increases为什么我的多线程示例中的时间随着线程数的增加而增加
【发布时间】:2012-06-20 07:52:53
【问题描述】:

如何编写在给定线程数中运行程序并显示每个线程所用时间的结果的多线程 Windows 应用程序。我尝试创建它,但我可以看到我的程序显示不正确的结果,这意味着当我增加线程数时,每个线程所花费的时间也会增加(如消息框所示)。以下是我的代码:

private static void StartMultithread(long recordsToProcess, string connectionString, string stagingTableName, bool tableLockEnabled, bool transactionEnabled, int batchSize, bool userMultipleDatabases, bool userMultipleTables, bool userMultipleUsers, int bulkInsertTimeout)
 {
 Dictionary<string, Thread> threadPool = new Dictionary<string, Thread>();
 for (int i = 0; i < threadCount; i++)
 {
     Thread thread = new Thread(new ParameterizedThreadStart(delegate(object tid)
     {
         int ii = (int)tid;
         Core.BulkInsert bulkInsert1 = new Core.BulkInsert();
         string result1 = bulkInsert1.Insert(recordsToProcess, connectionString, stagingTableName, tableLockEnabled, transactionEnabled, batchSize, bulkInsertTimeout);
         MessageBox.Show (result1);
     }));

     thread.Name = i.ToString();
     threadPool.Add(thread.Name, thread);
 }

 for (int i = 0; i < threadCount; i++)
 {
     Thread thread = threadPool[i.ToString()];
     thread.IsBackground = true;
     thread.Start(i);
 }

 for (int i = 0; i < threadCount; i++)
 {
     Thread thread = threadPool[i.ToString()];
     thread.Join();
 }
}

因此,当我给 threadCount = 1 时,所用时间为 0.8 秒。 当它为 2 时,两个线程所花费的时间分别约为 1.2 秒。 当它是 3 时,它们单独花费的时间约为 1.7 秒。

bulkinsert1.Insert 将记录插入数据库,对于每个线程我传递不同的表(因此表锁不应该成为插入的瓶颈)

我希望所有线程都花费最少的时间,我想它应该是 0.8 秒,当 threadCount 为 1 时。

我是线程新手,如果我在任何地方错了,请纠正我

【问题讨论】:

  • 你有多少个 CPU 内核?如果你只有一个,那么任何时候任何一个线程都只能在一个 CPU 上运行。您至少需要两个核心才能看到这方面的任何改进。
  • 创建线程需要一些时间。请改用 System.Threading.ThreadPool.QueueUserWorkItem,这样您将在应用启动时使用 CLR 已创建的线程。
  • 顺便说一句,你用什么课来保证你的时间?如果您还没有,您可能应该使用 System.Diagnostics.Stopwatch。
  • 我使用的是同一个秒表
  • 标题错误。你应该问为什么时间在增加。由于共享资源,时间增加。

标签: c# .net winforms multithreading


【解决方案1】:

我不确定你是如何计时的,因为从提供的代码中看不到。

但是,假设bulkInsert1.Insert 是一个 IO 密集型操作(意味着您的线程主要等待 IO 操作完成),完成时间随着线程数的增加而增加是正常的。您有更多线程,但它们正在使用一些共享资源(例如 MB 总线、网卡、远程数据库等)。例如,如果数据库处理插入操作需要 0.8 秒,那么处理两个或多个同时执行相同操作的连接需要更长的时间是正常的——尤其是如果这些查询由于某种原因碰巧相互阻塞时.因此,您的线程的完成时间会增加。

【讨论】:

  • bulkinsert1 将记录插入数据库,对于每个线程我传递不同的表(因此表锁不应该成为插入的瓶颈)
  • @ImranRizvi 如前所述,阻塞只是一个例子。不同的表并不意味着没有其他共享资源。
猜你喜欢
  • 2014-04-27
  • 1970-01-01
  • 2021-05-06
  • 2016-07-04
  • 1970-01-01
  • 2021-12-13
  • 2014-01-08
  • 2021-11-22
相关资源
最近更新 更多