[英]Why is SetThreadAffinityMask ignored?
Why is SetThreadAffinityMask ignored?为什么 SetThreadAffinityMask 会被忽略? I'm trying to write a program that sets the Affinity of each process thread according to the value of IdealProcessor.
我正在尝试编写一个程序,根据 IdealProcessor 的值设置每个进程线程的亲和力。 But SetThreadAffinityMask is ignored.
但是 SetThreadAffinityMask 被忽略了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace ThreadAffinity
{
class Program
{
[DllImport("kernel32.dll")]
static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
[DllImport("kernel32.dll")]
static extern bool SetThreadAffinityMask(IntPtr hThread, IntPtr dwThreadAffinityMask);
[DllImport("kernel32.dll")]
static extern bool GetThreadIdealProcessorEx(IntPtr hThread, ref PROCESSOR_NUMBER lpIdealProcessor);
[DllImport("kernel32.dll")]
static extern bool CloseHandle(IntPtr hObject);
[StructLayout(LayoutKind.Sequential)]
public struct PROCESSOR_NUMBER
{
public ushort Group;
public byte Number;
public byte Reserved;
}
[Flags]
public enum ThreadAccess : int
{
TERMINATE = (0x0001),
SUSPEND_RESUME = (0x0002),
GET_CONTEXT = (0x0008),
SET_CONTEXT = (0x0010),
SET_INFORMATION = (0x0020),
QUERY_INFORMATION = (0x0040),
SET_THREAD_TOKEN = (0x0080),
IMPERSONATE = (0x0100),
DIRECT_IMPERSONATION = (0x0200),
THREAD_ALL_ACCESS = (0x1F03FF)
}
static void Main(string[] args)
{
Console.WriteLine("Enter process id:");
int processId = Convert.ToInt32(Console.ReadLine());
Process process = Process.GetProcessById(processId);
foreach (ProcessThread thread in process.Threads)
{
IntPtr hThread = OpenThread(ThreadAccess.QUERY_INFORMATION, false, (uint)thread.Id);
PROCESSOR_NUMBER processorNumber = new PROCESSOR_NUMBER();
GetThreadIdealProcessorEx(hThread, ref processorNumber);
Console.WriteLine("Thread {0} ideal processor is {1}", thread.Id, processorNumber.Number);
SetThreadAffinityMask(hThread, (IntPtr)(1 << processorNumber.Number));
CloseHandle(hThread);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
I can't deny that with 99% probability I'm an idiot, that's why I came here to ask for your help.我不能否认 99% 的可能性我是个白痴,这就是为什么我来这里寻求你的帮助。
upd1: The program properly detects idealprocessor, but doesn't set affinity to the thread. upd1:程序正确检测到idealprocessor,但没有设置线程的亲和力。
As @RaymondChen said正如@RaymondChen所说
Per documentation: This handle must have the THREAD_SET_INFORMATION or THREAD_SET_LIMITED_INFORMATION access right and the THREAD_QUERY_INFORMATION or THREAD_QUERY_LIMITED_INFORMATION access right.
根据文档:此句柄必须具有 THREAD_SET_INFORMATION 或 THREAD_SET_LIMITED_INFORMATION 访问权限以及 THREAD_QUERY_INFORMATION 或 THREAD_QUERY_LIMITED_INFORMATION 访问权限。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.