Using SetThreadAffinityMask function imported from kernel32.dll
I am trying to set thread affinity using SetThreadAffinityMask
function imported from kernel32.dll in C# code of mine.
This is how I import it:
[DllImport("kernel32.dll")]
static extern Int开发者_如何学运维Ptr SetThreadAffinityMask(IntPtr hThread, IntPtr dwThreadAffinityMask);
I am creating 3 threads
Thread t1 = new Thread(some delegate);
Thread t2 = new Thread(some delegate);
Thread t3 = new Thread(some delegate);
I wish to set thread affinity for t1, t2 an t3 for which I am using `SetThreadAffinityMask function.
But I am not getting how to pass parameters to this function.
SetThreadAffinityMask
takes two parameters
HANDLE hThread
DWORD_PTR dwThreadAffinityMask
Please help me in using SetThreadAffinityMask
function in C#.
Don't.
Managed threads <> native threads.
The only option supported for managed threads is to call Thread.BeginThreadAffinity/EndThreadAffinity around code which requires thread affinity.
Can't you use Thread.BeginThreadAffinity?
First of all you should be sure that your .NET thread runs on a particular operating system thread. Wrap the logic with Thread.BeginThreadAffinity();
and Thread.EndThreadAffinity();
to do that.
Use GetCurrentThread()
from kernel32.dll
to get current thread handle.
Thread affinity mask dwThreadAffinityMask
described in documentation:
A thread affinity mask is a bit vector in which each bit represents a logical processor that a thread is allowed to run on. is allowed to run on.
e.g. if you want to run your thread on the second and fourth logical processors use 0x0A
mask.
Code sample:
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentThread();
[DllImport("kernel32.dll")]
static extern IntPtr SetThreadAffinityMask(IntPtr hThread, IntPtr dwThreadAffinityMask);
Thread t1
= new Thread(() =>
{
try
{
Thread.BeginThreadAffinity();
SetThreadAffinityMask(GetCurrentThread(), new IntPtr(0x0A));
// <your thread logic here>
}
finally
{
Thread.EndThreadAffinity();
}
});
I found an example on using this function here.
精彩评论