Click here to Skip to main content
15,885,782 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi All,

I have multiple tasks and i need to run them on specific multiple cores or processors

simultaneously. For Example, if i have two different tasks or just one task but will run it twice

i want to run these two tasks on specific cores or processors simultaneously like task1 will run

on processor1 and task2 will run on processor2 at the same time. i know how to run each specific

processor but i do not know how to run them simultaneously. I was trying to use multithreading

then task parallel library to run different tasks on specific processors at the same time but i

failed. in below code, i was trying to use multithreading but it doesnt work or can i use task

parallel library???

PLEASE HELP!!!!!


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace ConsoleApplication14
{
    class Program
    {
        
        public static double DumbCountSqr(int dumnum)
        {

            Random random = new Random();
            int randomNumber = random.Next(0, 10);
            double result = 0;
            for (int i = 1; i < 10000; i++)
            {
                for (int j = 1; j < 10000; j++)
                {
                    result += random.Next(0, 10) * Math.Sqrt(i) * Math.Sqrt(j) + Math.Abs(Math.Sqrt(i));
                }
            }
            return result;
        }

        public static void Main()
        {

            Thread t = new Thread(new ThreadStart(Go));
            t.Start();


            for (int i = 0; i < 1; i++)
            {

                Process Proc = Process.GetCurrentProcess();
                long AffinityMask = (long)Proc.ProcessorAffinity;

                AffinityMask = 0x0004;//processor    3
                Proc.ProcessorAffinity = (IntPtr)AffinityMask;

                var result1 = DumbCountSqr(i);
                Console.WriteLine("result1 =  " + result1);

            }
        }
        
        
       public static void Go()
        {

            for (int i = 0; i < 1; i++)
            {
                
                    Process Proc = Process.GetCurrentProcess();
                    long AffinityMask = (long)Proc.ProcessorAffinity;

                    AffinityMask = 0x0001;//processor    1
                    Proc.ProcessorAffinity = (IntPtr)AffinityMask;

                    var result2 = DumbCountSqr(i);
                    Console.WriteLine("result2 =  " + result2);
   
            }
   
        }

    }
}
Posted
Updated 30-Jun-21 21:47pm

Let me give you a really short introduction.

You can use threads in a way abstracted from the CPU cores. And the OS associates cores with threads using its own. In almost all cases, this is the very best option. I would not recommend touching process and thread affinity at all. The cases when you may find it beneficial to touch affinity are very rare, and I would call all of them "really bad cases". For example, if you have some really bad piece of hardware which requires extensive periodic polling (really good devices work by interrupts), you may decided to sacrifice one core to this problem in order to make behavior processes/thread using other cores more predictable, especially of some are more or less mission-critical (I won't risk saying "real-time" which would be a very different and more advanced topic, hardly about Windows). Or, just the opposite, you may have just one very mission-critical application, to dedicate a core to it; but this is hard to do, because other application may interfere, as they "don't know" about your decision.

If you want to consider TPL (Parallel), you would move in directly opposite way: not only Tasks are abstracted from cores, it is abstracted from threads. Actually, TPL is based on threads, but the developer, in general case, does not know what piece of code is executed on which thread, which pieces run in parallel and which are on the same thread. TPL automatically dispatches code between threads.

Basically, that's all. If you have some specific goals (really special and specific), you may get a chance to get some practical advice, if you share them.

—SA
 
Share this answer
 
v4
Hi, I am going to give you two solution and you choose one or another depending in your needs. I didn't use your code demo as a guide but the text of your question.

- Choose the ThreadApproach if you want to have explicit control over the thread that will run your task including the processor it will run on, stack size and so on.

- Choose the TaskApproach if you only care about doing the work fast and in parallel by letting the runtime to do it for you.

C#
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication
{
   class Program
   {
      static void MyTask() { /*Implement your long running task here*/ }

      static void ThreadApproach()
      {
         var t1 = new Thread(MyTask);
         var t2 = new Thread(MyTask);

         // Bound your threads to a specific processor if you want and so on.

         t1.Start();
         t2.Start();

         // The tasks should start running simultaneously at this point.

         // Optional if you want to synchronously wait for completion.
         t1.Join();
         t2.Join();
      }

      static void TaskApproach()
      {
         var t1 = Task.Run(() => MyTask());
         var t2 = Task.Run(() => MyTask());

         // Optional if you want to synchronously wait for completion.
         // However I recomend you async/await if you are going to work with Tasks.
         // But this is another topic.
         Task.WaitAll(t1, t2);
      }

      static void Main(string[] args)
      {
         // Use one of these:
         ThreadApproach();
         // Or
         TaskApproach();

         Console.WriteLine("Job Completed!");
         Console.ReadLine();
      }
   }
}
 
Share this answer
 
I tried both methods , threadapproach and taskapproach, but i couldnt get two or more tasks start to run simultaneously because when i check cpu utilization, i see that only one of the specific processors is working with 100%, but what i want is two or more specific processors should work with 100% or near 100% simultaneously.

If i summarize what i am trying to do is, I want to do parallel computing but i want to specify which processors should work in parallel.

Here is your code, i did some modifications, but it doesnt do what i want.

First, i have a mathematical function, a random calculation, then i would like to have processor 2 and 3 should work on this task simultaneously to get the result.
When i run the code, only one of the specific processor is working with 100%, not both of them simultaneously.

C#
<pre>using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ConsoleApplication
{
    class Program
    {
        public static double DumbCountSqr(int dumnum)
        {
            // My sample task - just a mathematical calculation

            Random random = new Random();
            int randomNumber = random.Next(0, 10);
            double result = 0;
            for (int i = 1; i < 20000; i++)
            {
                for (int j = 1; j < 15000; j++)
                {
                    result += random.Next(0, 10) * Math.Sqrt(i) * Math.Sqrt(j) + Math.Abs(Math.Sqrt(i));
                }
            }
            return result;
        }

        public static void MyTask()
        {
            for (int i = 0; i < 1; i++)
            {
                // the task,mathematical calculation, should run only on processor 3

                Process Proc = Process.GetCurrentProcess();
                long AffinityMask = (long)Proc.ProcessorAffinity;

                AffinityMask = 0x0004;//processor    3
                Proc.ProcessorAffinity = (IntPtr)AffinityMask;

                var result1 = DumbCountSqr(i);
                Console.WriteLine("result1 =  " + result1);

            } 
        }
        

        public static void MyTask2()
        {
            for (int i = 1; i < 2; i++)
            {
                // the task,mathematical calculation, should run only on processor 2

                Process Proc = Process.GetCurrentProcess();
                long AffinityMask = (long)Proc.ProcessorAffinity;

                AffinityMask = 0x0002;//processor    2
                Proc.ProcessorAffinity = (IntPtr)AffinityMask;

                var result2 = DumbCountSqr(i);
                Console.WriteLine("result2 =  " + result2);

            }
        }


       
        static void ThreadApproach()
        {
            var t1 = new Thread(MyTask);
            var t2 = new Thread(MyTask2);

            // Bound your threads to a specific processor if you want and so on.
            // I do not know how to bound threads to a specific processor???????


            // processor 2 and 3 should start to work on the task simultaneously 
            // with the way i bound tasks to processors but they do not start simultaneously???????
            t1.Start();
            t2.Start();

            // The tasks should start running simultaneously at this point.
            // Tasks do not start running simultaneously because when i check cpu utilization
            // only one processor is working with 100%

            // Optional if you want to synchronously wait for completion.
            t1.Join();
            t2.Join();
        }
        

        /*
        static void TaskApproach()
        {
            var t1 = Task.Factory.StartNew(() => MyTask());
            var t2 = Task.Factory.StartNew(() => MyTask2());

           
            

            // Optional if you want to synchronously wait for completion.
            // However I recomend you async/await if you are going to work with Tasks.
            // But this is another topic.
            Task.WaitAll(t1, t2);
        }
        */
        static void Main(string[] args)
        {
            // Use one of these:
            ThreadApproach();
            // Or
            // TaskApproach();

            Console.WriteLine("Job Completed!");
            Console.ReadLine();
        }
    }
}
 
Share this answer
 
Comments
gggustafson 21-Mar-14 14:37pm    
One again, read Sergey's answer. DO NOT try to do what you are trying to do. I have run applications with 37 threads. Whenever I tried to play with affinities, I always reduced overall performance. Affinity is something that Cotter worked out very well. I don't think you can beat his work.

What are the for loops for in each task? they both only execute once - no need for the loop.

The working function may differ in execution time for each invocation. Remove the randomness to be able to make inferences about the thread execution time.

Strongly recommend you read Parallel computing and processor affinity. Never underestimate the Windows Vista Scheduler that applies to all OSs not just Vista.
Hi, the problem in your design is that you are using a Processor level Affinity Mask. If you set if to 2, then all your threads will run on processor 2 and if you set it to 3, then all your threads will run on processor 3.

If you want that thread 1 run on processor 2 and thread 2 run on processor 3 use the following code:

C#
Process.GetCurrentProcess().Threads[1].ProcessorAffinity = (IntPtr)2;
Process.GetCurrentProcess().Threads[2].ProcessorAffinity = (IntPtr)3;


Remember that Threads[0] is your main thread, and Threads[1] and [2] are your newly created threads. For more help please read the MSDN on this topic: ProcessThread.ProcessorAffinity Property

Yandy
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900