moel@344: /* moel@344: moel@344: This Source Code Form is subject to the terms of the Mozilla Public moel@344: License, v. 2.0. If a copy of the MPL was not distributed with this moel@344: file, You can obtain one at http://mozilla.org/MPL/2.0/. moel@344: moel@432: Copyright (C) 2010-2014 Michael Möller moel@344: moel@238: */ moel@238: moel@238: using System; moel@238: using System.Runtime.InteropServices; moel@238: moel@238: namespace OpenHardwareMonitor.Hardware { moel@238: moel@238: internal static class ThreadAffinity { moel@238: moel@238: public static ulong Set(ulong mask) { moel@238: if (mask == 0) moel@238: return 0; moel@238: moel@238: int p = (int)Environment.OSVersion.Platform; moel@238: if ((p == 4) || (p == 128)) { // Unix moel@238: ulong result = 0; moel@238: if (NativeMethods.sched_getaffinity(0, (IntPtr)Marshal.SizeOf(result), moel@238: ref result) != 0) moel@238: return 0; moel@238: if (NativeMethods.sched_setaffinity(0, (IntPtr)Marshal.SizeOf(mask), moel@238: ref mask) != 0) moel@238: return 0; moel@238: return result; moel@432: } else { // Windows moel@432: UIntPtr uIntPtrMask; moel@432: try { moel@432: uIntPtrMask = (UIntPtr)mask; moel@432: } catch (OverflowException) { moel@432: throw new ArgumentOutOfRangeException("mask"); moel@432: } moel@432: return (ulong)NativeMethods.SetThreadAffinityMask( moel@432: NativeMethods.GetCurrentThread(), uIntPtrMask); moel@238: } moel@238: } moel@238: moel@238: private static class NativeMethods { moel@238: private const string KERNEL = "kernel32.dll"; moel@238: moel@238: [DllImport(KERNEL, CallingConvention = CallingConvention.Winapi)] moel@238: public static extern UIntPtr moel@238: SetThreadAffinityMask(IntPtr handle, UIntPtr mask); moel@238: moel@238: [DllImport(KERNEL, CallingConvention = CallingConvention.Winapi)] moel@238: public static extern IntPtr GetCurrentThread(); moel@238: moel@238: private const string LIBC = "libc"; moel@238: moel@238: [DllImport(LIBC)] moel@238: public static extern int sched_getaffinity(int pid, IntPtr maskSize, moel@238: ref ulong mask); moel@238: moel@238: [DllImport(LIBC)] moel@238: public static extern int sched_setaffinity(int pid, IntPtr maskSize, moel@238: ref ulong mask); moel@238: } moel@238: } moel@238: } moel@238: