/// <summary> /// Sets the processor group and the processor cpu affinity of the current thread. /// </summary> /// <param name="group">A processor group number.</param> /// <param name="cpus">A list of CPU numbers. The values should be /// between 0 and <see cref="Environment.ProcessorCount"/>.</param> public void SetThreadProcessorAffinity(ushort groupId, params int[] cpus) { if (cpus == null) { throw new ArgumentNullException(nameof(cpus)); } if (cpus.Length == 0) { throw new ArgumentException("You must specify at least one CPU.", nameof(cpus)); } // Supports up to 64 processors long cpuMask = 0; foreach (var cpu in cpus) { if (cpu < 0 || cpu >= Environment.ProcessorCount) { throw new ArgumentException("Invalid CPU number."); } cpuMask |= 1L << cpu; } var hThread = GetCurrentThread(); var previousAffinity = new _GROUP_AFFINITY { Reserved = new ushort[3] }; var newAffinity = new _GROUP_AFFINITY { Group = groupId, Mask = new UIntPtr((ulong)cpuMask), Reserved = new ushort[3] }; SetThreadGroupAffinity(hThread, ref newAffinity, ref previousAffinity); }
private static extern Boolean SetThreadGroupAffinity( IntPtr hThread, ref _GROUP_AFFINITY GroupAffinity, ref _GROUP_AFFINITY PreviousGroupAffinity);
public static void SetAffinity(LogicalProcessorInfo lpInfo) { //---------------------------------------------- // Intel Corporation // Copyright © 2009/2010 - All Rights Reserved // Department : SST/NTE // Written by : Bill Hines - [email protected] // Modified by : N/A // Date : 12/4/2009 //---------------------------------------------- const uint DUPLICATE_SAME_ACCESS = 0x00000002; IntPtr CP = Process.GetCurrentProcess().Handle; IntPtr hThread = IntPtr.Zero; if (DuplicateHandle(CP, GetCurrentThread(), CP, out hThread, DUPLICATE_SAME_ACCESS, false, DUPLICATE_SAME_ACCESS)) { if (!CheckForGPPExEntryPoint()) { UIntPtr Foo = SetThreadAffinityMask(hThread, new UIntPtr((ulong)Math.Pow(2, lpInfo.AbsoluteProcessor))); } else { _GROUP_AFFINITY PreviousGA = new _GROUP_AFFINITY(); _GROUP_AFFINITY pGA = new _GROUP_AFFINITY(); pGA.Group = lpInfo.GroupNumber; pGA.Mask = lpInfo.ProcessorMask; pGA.Reserved = new ushort[3]; PreviousGA.Reserved = new ushort[3]; bool rv = false; rv = SetThreadGroupAffinity(hThread, ref pGA, ref PreviousGA); } } bool rv1 = CloseHandle(hThread); }
private static extern Boolean SetThreadGroupAffinity(IntPtr hThread, ref _GROUP_AFFINITY GroupAffinity, ref _GROUP_AFFINITY PreviousGroupAffinity);
private static extern bool GetThreadGroupAffinity(IntPtr hThread, ref _GROUP_AFFINITY GroupAffinity);
private static extern bool GetNumaNodeProcessorMaskEx( [In] ushort Node, ref _GROUP_AFFINITY ProcessorMask);