The Computer Oracle

When you start multiple threads on a multi core processor, are they guaranteed to be processed by different cores?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Ancient Construction

--

Chapters
00:00 When You Start Multiple Threads On A Multi Core Processor, Are They Guaranteed To Be Processed By Di
00:24 Answer 1 Score 17
00:56 Accepted Answer Score 20
01:30 Thank you

--

Full question
https://superuser.com/questions/605039/w...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#cpu #c# #threading

#avk47



ACCEPTED ANSWER

Score 20


You cannot guarantee in .Net that two Threads 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 Threads (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.




ANSWER 2

Score 17


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.