4

所以我想我理解并行编程和多线程的概述概念,但我想知道是否可以实现多进程多线程应用程序。如果这是有道理的,那么在查看多线程的一些描述时,它可以在一个处理器上运行,但是如果您可以使用并行处理多个内核,您还可以在多个内核上进行多线程处理吗?如果可以的话,有人可以给我看一个简单的例子for loop吗?

多线程示例:

public class Test
{
    static void Main()
    {
        Counter foo = new Counter();
        ThreadStart job = new ThreadStart(foo.Count);
        Thread thread = new Thread(job);
        thread.Start();

        for (int i=0; i < 5; i++)
        {
            Console.WriteLine ("Main thread: {0}", i);
            Thread.Sleep(1000);
        }
    }
}

public class Counter
{
    public void Count()
    {
        for (int i=0; i < 10; i++)
        {
            Console.WriteLine ("Other thread: {0}", i);
            Thread.Sleep(500);
        }
    }
}

并行示例:

int n = ...
Parallel.For(0, n, i =>
{
   // ... 
});
4

1 回答 1

2

Distribution of tasks to available logical CPUs is the task of the operating system. If you write a multithreaded application the OS will manage distributing the various threads to the hardware processors in the system. There is nothing you have to do as a programmer to make this happen.

You can, however, manage this directly - associating a specific thread to run on a specific core or subset of logical processors, but generally this is less efficient than allowing the OS to manage hardware allocation since it has broader awareness of all processes running on the system and in most all cases handles the allocation in the most efficient way.

In brief, if your application is multithreaded then it will run on as many available cores as the system provides.

于 2013-03-29T14:58:48.973 回答