views:

354

answers:

4

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 ?

+3  A: 

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.

TomTom
what Techee means to do is to set Thread's affinity, like you can with a Process. I am not aware that this is possible with .net thread classes.
Axarydax
Windows has thread affinity, you could P/Invoke the appropriate functions, using the native ID of the threads (so the simplest approach is for each thread to set its own affinity). But like priorities, it is almost always the wrong approach.
Richard
not sure what he means, because thread affinity makes simply no sense in the context of the question either. Thread affinity would tie the process to specific processors - and not solve the base problem of having a threaded application to start with.
TomTom
+2  A: 

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.

Jason Williams
Indeed, and if you are not seeing multiple cores in use, then there is something in your code (or the code you call) that is preventing this.
Richard
+2  A: 

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).

Lucero
+3  A: 
Kushal Waikar
This is for a complete process only, and not for single threads in a process which should effectively run in parallel in the same process (which I assume is what Techee is looking for).
Lucero
Yep. I do agree :-)
Kushal Waikar