Techee
Techee

Reputation: 1825

How to use hardware threads in C# dot net code running on multicore machine?

How to use hardware threads in C sharp code running on multi core machine ? Any example will be appreciated.

I wish to run the two threads parallelly on two cores of my machine. If I create normal software threads in C sharp they may run on single core. Is it possible to run these two threads implicitly parallel on two cores so as to get better performance ?

Upvotes: 4

Views: 2662

Answers (4)

Kushal Waikar
Kushal Waikar

Reputation: 2994

You may have a look at "Processor affinity".

You can use System.Diagnostics namespace to force a process to run on a specific processor. The following line will change current process affinity to processors 1 & 2

System.Diagnostics.Process.GetCurrentProcess().ProcessorAffinity = (System.IntPtr)3;

Process.ProcessorAffinity Property gets or sets the processors on which the threads in this process can be scheduled to run.

The following table shows a selection of ProcessorAffinity values for an two-processor system.

  Value   Description

    0   Not allowed
    1   Use processor 1
    2   Use processor 2
    3   Use both processors 1 and 2

For more details please go through following MSDN reference--> http://msdn.microsoft.com/en-us/library/system.diagnostics.process.processoraffinity.aspx

Upvotes: 4

Lucero
Lucero

Reputation: 60190

There is usually no good reason to do this. Windows knows more about the available resources in order to schedule and distribute them well than you do in your application.

See also this CodeProject article, which shows the point pretty well (along with some ways to set the processor affinity).

Upvotes: 3

Jason Williams
Jason Williams

Reputation: 57902

If you schedule software threads, they will automatically be run on any processor core that is available - e.g. if you have two or four processor cores (hardware), then your computer will run your two threads in parallel (if the cores aren't busy doing something else at the time).

i.e. You don't need to do anything more than creating the threads, and the computer will do whatever it can to utilise your hardware as well as possible.

Upvotes: 3

TomTom
TomTom

Reputation: 62093

Ah, you use THREADS. Like in System.Threading.Thread. All known windows implementations of .NET map those to hardware threads.

You can not create "normal software threads" in C#. Where did you get this idea from?

And the scheduler will schedule all threads as it can - i.e. with multiple cores they will run in parallel.

Upvotes: 3

Related Questions