How to find which core your thread is scheduled on?


no comments

How to find which core your thread is scheduled on?

this post is short and quit simple,

it deal with technique of finding out which core attached to the current thread.


in general finding the core is a matter of diagnostic, it may give some insights like

whether we are using the CPU cache line in optimal way.

the simplest way (and a very recommended one) is to profile your application

using the Visual Studio Concurrent Profiler (which available on VS 2010 ultimate).

Parallel, core, Tpl, Task, Task.Factory, CPU

in case that you have the need of finding the attached core at runtime from C# code,

you can PInvoke GetCurrentProcessorNumber as shown in the following snippet:

Code Snippet
  1. [DllImport("Kernel32.dll"), SuppressUnmanagedCodeSecurity]
  2. public static extern int GetCurrentProcessorNumber();
  4. static void Main(string[] args)
  5. {
  6.     Parallel.For (0, 10 , state => Console.WriteLine("Thread Id = {0}, CoreId = {1}",
  7.         Thread.CurrentThread.ManagedThreadId,
  8.         GetCurrentProcessorNumber()));
  9.     Console.ReadKey();
  10. }

also available at:



do not assume that single thread will be schedule on single core,

thread may switch cores after context switching.

this technique is also limited for Windows Vista and above.




kick it on

Digg This
Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>