An example of parallel programming with multithreading

15,081

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.

Share:
15,081
Kirsty White
Author by

Kirsty White

Im new to asp.net

Updated on June 04, 2022

Comments

  • Kirsty White
    Kirsty White almost 2 years

    So I think I understand the overview concept of parallel programming and multithreading, but I was wondering if you can achieve multi-process multi-threaded applications. If that makes sense, when looking at some of the descriptions of multi-threading it can be run on one processor but if you can process on multiple cores using parallel can you also multi-thread on multiple cores? If you can, could someone show me a simple example of this, using a for loop maybe?

    Multi-threaded example:

    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);
            }
        }
    }
    

    Example of parallel:

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