0

When I use

int threadnum = Thread.CurrentThread.ManagedThreadId;

it returns a value which can exceed the number of logical cores. Of course this is because there can be way more threads than logical cores. The code line isn't what I'm looking for.

What I would like, at least for a given run of the program, is a way to get which logical core the thread is running on. So if there are 48 logical cores, I would like to know which of those cores the thread was running on.

Not sure if the system numbers the logical cores in a consistent way, but at the least for a given run of the program, I would like to know which logical core a thread was running on.

With openMP in C++ it was simple: omp_get_thread_num()

The thread number of the thread team would at least be numbered from 0 to the number of logical cores - 1.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • [GetCurrentProcessorNumber](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentprocessornumber) (or the ~Ex version) via pinvoke. – Wyck Apr 07 '22 at 16:10
  • Oh, wait a minute: Does this need to be os-agnostic? In that case p/invoke to a windows API would only be a part of a solution. – Fildor Apr 07 '22 at 16:22

1 Answers1

0

You can try something like GetCurrentProcessorNumber() method https://stackoverflow.com/a/49284774

However, you'd like to ask yourself what knowledge the fact will give you. Here are some considerations:

  • "logical" cores/threads are not obliged to match physical ones
  • if we have async/await code, there is even no warranty the code continuation will the on same logical thread (because it is about synchronizations contexts, not threads, and that contexts may be tricky)
  • and here we're not talking about affinity masks, NUMAs etc

So, it seems like "X-> Y" problem. Could you describe your final goal, not interim milestones?

Yury Schkatula
  • 5,291
  • 2
  • 18
  • 42
  • let's not answer duplicates, please. – Wyck Apr 07 '22 at 16:16
  • @Wyck it's not about duplications, as 1) it's not a lonely link like the comment above; 2) thanks to BigData, I had no chance to see that comments before sending the response – Yury Schkatula Apr 07 '22 at 16:18