When you start multiple threads on a multi core processor, are they guaranteed to be processed by different cores?
Solution 1:
You cannot guarantee in .Net that two Thread
s run on two separate cores. In fact, you also cannot guarantee that one Thread
will run on only one core(!).
This is because managed threads are not the same as OS threads - a single managed Thread may use multiple OS threads to support it. In C#, you only ever deal directly with managed Thread
s (at least, without resorting to p/invoke to call the WinAPI threading functions, which you should never do).
However, the .Net and Windows thread schedulers are very good at what they do - they wouldn't run two threads on a single core while a second core sits completely idle. So, in general, you don't need to worry about it.
Solution 2:
No, the OS and CPU will decide what to run and when. in the simple example you have shown, to the exclusion of other tasks, yes those would most likely run in parallel on separate cores, but there is rarely a guarantee that that will be the case.
You can use the thread affinity to attempt to take some control over the allocation of a core to a given thread.
Also consider scheduling priorities to stack the deck in terms of which threads should be entirely parallel, and which can wait.