8

I have a quad core CPU, and lets say I always want to start a Thread on the second core.

Is that possible in C#?

Sam
  • 7,252
  • 16
  • 46
  • 65
Rosmarine Popcorn
  • 10,761
  • 11
  • 59
  • 89
  • 1
    See [How Can I Set Processor Affinity in .NET?](http://stackoverflow.com/questions/2510593/how-can-i-set-processor-affinity-in-net). – Matthew Flaschen Jul 05 '11 at 14:36
  • Possible duplicate of [How Can I Set Processor Affinity in .NET?](https://stackoverflow.com/questions/2510593/how-can-i-set-processor-affinity-in-net) – Yoh Deadfall Apr 18 '18 at 20:34
  • Check these discussions: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/a55733db-cac0-4ccb-a3cc-a584742b41f9/ http://www.eggheadcafe.com/community/aspnet/2/10156145/thread-affinity.aspx http://www.gamedev.net/topic/477794-c-multi-threading-quad-core-thread-affinity/ – ata Jul 05 '11 at 14:43

3 Answers3

9

Yes. Check out ProcessorAffinity for Windows or SetProcessorAffinity for XBox XNA.

This is also discussed on another Stackoverflow question.

Community
  • 1
  • 1
Kynth
  • 2,597
  • 1
  • 18
  • 24
8

Yes, take a look at the ProcessorAffinity property for the thread.

Chris Van Opstal
  • 36,423
  • 9
  • 73
  • 90
2

Set ProcessorAffinity of the process:

0x0001 = 0000 0001 - run on 1st core
                 ↑
0x0002 = 0000 0010 - run on 2nd core
                ↑
0x0003 = 0000 0011 - run on 1st and 2nd core
                ↑↑
0x0004 = 0000 0100 - run on 3rd core
               ↑

Simple code:

using (var process = Process.GetCurrentProcess())
{
  // only run on core number 1
  process.ProcessorAffinity = (IntPtr) 0x0001;
}
Timeless
  • 7,338
  • 9
  • 60
  • 94