4

In C#, is there any method to get the cpu id (or core number) of the core that is executing a thread? I have a quad core processor and I wanted to know that on spanning some threads, which cores do they get alloted?

I found out that System.Environment.ProcessorCount gives the total number of cpus present, but is there any way to know which specific cpu instance is executing a given thread.

7
  • 7
    A thread won't necessarily remain on one particular CPU throughout its lifetime. Commented May 30, 2011 at 17:34
  • 5
    a thread can switch cores in the middle of a line of code Commented May 30, 2011 at 17:37
  • The only way you can control threads allocation is using cpu affinity. Commented May 30, 2011 at 17:42
  • Why do you want to know this? There's probably a more appropriate technique. Commented May 30, 2011 at 17:53
  • @bestsss, you can't do that in C# unsafe code. This will require some assm code. Something like asm { mov eax,1; cpuid; shr ebx,24; } after which the ebx register would have the APIC, I have never used managed C++ maybe it could be done with that. Commented May 30, 2011 at 18:15

1 Answer 1

5

I do not know of a native .NET function that can provide this. But if you are prepared to use P/Invoke and are running on Windows 2003, Vista or later then you can call GetCurrentProcessorNumber.

Of course this will only give you the CPU (core) that is executing the thread at that particular time slice and the next time the thread is scheduled it might be running on a completely different core even though the OS will strive to schedule a thread on the same core for performance reasons.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.