【问题标题】:C# Threading - Multiple threads spawned, only 1 or 2 are executing others waitingC# 线程 - 产生多个线程,只有 1 或 2 个正在执行其他线程等待
【发布时间】:2010-08-19 06:38:41
【问题描述】:

我在下面有这段代码,我在其中生成了几个线程,通常大约 7 个,然后加入它们以等待全部完成:

            List<Thread> threads = new List<Thread>();
            Thread thread;
            foreach (int size in _parameterCombinations.Keys)
            {
                thread = new Thread(new ParameterizedThreadStart(CalculateResults));
                thread.Start(size);
                threads.Add(thread);
            }

            // wait for all threads to finish
            for (int index = 0; index < threads.Count; index++)
            {
                threads[index].Join();
            }

当我检查这一点时,大多数时候只有一两个线程同时运行,当我重新运行应用程序时只有一两次,所有线程都执行了。

有没有办法强制所有线程开始执行?

非常感谢。

【问题讨论】:

  • 由于我们不知道 CalculateResults 的定义,因此很难判断此方法是否会在某些时候阻塞,但这可以解释观察到的行为。
  • 您的机器上有多少个内核?只有这么多线程实际上可以并行运行。
  • 计算任务需要多长时间?
  • 卢克,这是不正确的。线程可以被执行和冻结。
  • @luke:正如 Adibe 指出的那样,这是不正确的。即使是单核且没有超线程,操作系统也会为每个线程提供自己的切片。

标签: c# .net multithreading execution


【解决方案1】:

你的代码没问题..我修改了它以向你展示线程的执行不限于 2 个线程。 我会在计算过程中寻找问题..

class Program
{
    static void Main(string[] args)
    {
        List<Thread> threads = new List<Thread>();
        Thread thread;
        for (int i = 0; i < 7; i++)
        {
            thread = new Thread(new ParameterizedThreadStart(CalculateResults));
            thread.Start();
            threads.Add(thread);
        }

        // wait for all threads to finish
        for (int index = 0; index < threads.Count; index++)
        {
            threads[index].Join();
        }
    }

    static void CalculateResults(object obj)
    {
        Console.WriteLine("Thread number " + Thread.CurrentThread.ManagedThreadId + " is alive");
        Thread.Sleep(1000);
        Console.WriteLine("Thread number " + Thread.CurrentThread.ManagedThreadId + " is closing");
    }
}

【讨论】:

  • Adibe,感谢您为我指明了正确的方向。我用 Thread.Sleep 替换了对 CPU 密集型函数的调用,它运行良好。计算函数会消耗所有 CPU,而且我怀疑操作系统很难切换线程。
  • @misha-r:您的计算线程将根据需要被操作系统抢占和重新调度。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
  • 2015-02-22
  • 1970-01-01
相关资源
最近更新 更多