views:

320

answers:

3

Hi,

If I have a multi-thread program, how can I know on which core each thread run ?

Is there any another solution for win XP in C# ?

I try this:

[DllImport("ntdll"), SuppressUnmanagedCodeSecurity]
public static extern int NtGetCurrentProcessorNumber();

and I get this exception:

System.EntryPointNotFoundException was unhandled Message="Unable to find an entry point named 'NtGetCurrentProcessorNumber' in DLL 'ntdll'." Source="XP_Multicore_try_0" TypeName="" StackTrace: at XP_Multicore_try_0.Program.NtGetCurrentProcessorNumber() at XP_Multicore_try_0.Program.loop() in C:\Documents and Settings\evyatarv\Desktop\XP_Multicore_try_0\XP_Multicore_try_0\Program.cs:line 24 at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()

Thanks, Evyatar

A: 

I'm not sure there is a good way. While Win32 offers the SetThreadAffinityMask() function which returns the existing affinity mask, the .NET thread is not safe to associate with an operating system thread as per this question.

Jesse C. Slicer
I know this function, but I don't want to use is (for testing reasons)
Evyatar
A: 

According to MSDN, NtGetCurrentProcessorNumber may be altered or unavailable in future versions of Windows. Applications should use the GetCurrentProcessorNumber function from Kernel32.dll instead.

GetCurrentProcessorNumber() isn't available on all versions of Windows, either. It's available on Vista and above, or Windows Server 2003 and above. That means that trying to use it on XP will fail as well.

If you're going to use API calls, you should at least read the documentation first. :-)

That being said, I don't know of any way on XP and earlier to determine what core or processor a thread is being run on. That's probably why they added GetProcessorNumber() to the API starting with Vista.

Ken White
I have read the API (that's why I'm here.. :) ), Thanks any way..
Evyatar
+1  A: 

First you need to identify what "core number" you want. Each core has several numbers associated with it. In this case I am assuming you mean the OS affinity index of the core.

In that case, assuming an x86 CPU, you can get the APIC number of the core (using the CPUID instruction), then use it as an index in a table of equivalence to the affinity index.

Of course you will have to make the table of equivalence yourself ahead of time. You could do that by going to each core (by setting affinity, thus knowing the affinity index) and retrieving its APIC.

Note that I don't know how you would do that in C#, I'm no C# expert. But it is fairly easy in C, and even easier in assembly.

Juice