Hardware/ThreadAffinity.cs
author moel.mich
Tue, 30 Dec 2014 22:49:32 +0000
changeset 432 7b859a06eecb
parent 344 3145aadca3d2
permissions -rwxr-xr-x
Fixed an OverflowException when trying to use (unsupported) 64-bit thread affinity masks on 32-bit systems.
     1 /*
     2  
     3   This Source Code Form is subject to the terms of the Mozilla Public
     4   License, v. 2.0. If a copy of the MPL was not distributed with this
     5   file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  
     7   Copyright (C) 2010-2014 Michael Möller <mmoeller@openhardwaremonitor.org>
     8 	
     9 */
    10 
    11 using System;
    12 using System.Runtime.InteropServices;
    13 
    14 namespace OpenHardwareMonitor.Hardware {
    15   
    16   internal static class ThreadAffinity {
    17   
    18     public static ulong Set(ulong mask) { 
    19       if (mask == 0)
    20         return 0;
    21         
    22       int p = (int)Environment.OSVersion.Platform;
    23       if ((p == 4) || (p == 128)) { // Unix
    24         ulong result = 0;
    25         if (NativeMethods.sched_getaffinity(0, (IntPtr)Marshal.SizeOf(result), 
    26           ref result) != 0)          
    27           return 0;
    28         if (NativeMethods.sched_setaffinity(0, (IntPtr)Marshal.SizeOf(mask), 
    29           ref mask) != 0)
    30           return 0;
    31         return result;
    32       } else { // Windows
    33         UIntPtr uIntPtrMask;
    34         try {
    35           uIntPtrMask = (UIntPtr)mask;
    36         } catch (OverflowException) {
    37           throw new ArgumentOutOfRangeException("mask");
    38         }
    39         return (ulong)NativeMethods.SetThreadAffinityMask(
    40           NativeMethods.GetCurrentThread(), uIntPtrMask);
    41       }
    42     }
    43   
    44     private static class NativeMethods {      
    45       private const string KERNEL = "kernel32.dll";
    46 
    47       [DllImport(KERNEL, CallingConvention = CallingConvention.Winapi)]
    48       public static extern UIntPtr
    49         SetThreadAffinityMask(IntPtr handle, UIntPtr mask);
    50 
    51       [DllImport(KERNEL, CallingConvention = CallingConvention.Winapi)]
    52       public static extern IntPtr GetCurrentThread();       
    53       
    54       private const string LIBC = "libc";
    55       
    56       [DllImport(LIBC)]
    57       public static extern int sched_getaffinity(int pid, IntPtr maskSize,
    58         ref ulong mask);
    59       
    60       [DllImport(LIBC)]
    61       public static extern int sched_setaffinity(int pid, IntPtr maskSize,
    62         ref ulong mask);  
    63     }  
    64   }
    65 }
    66