Hardware/ThreadAffinity.cs
author moel.mich
Tue, 30 Dec 2014 21:04:54 +0000
changeset 430 6b24e39f1b84
parent 238 bddc6e01840a
child 432 7b859a06eecb
permissions -rwxr-xr-x
Fixed Issue 651.
     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 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         return (ulong)NativeMethods.SetThreadAffinityMask(
    34           NativeMethods.GetCurrentThread(), (UIntPtr)mask);
    35       }
    36     }
    37   
    38     private static class NativeMethods {      
    39       private const string KERNEL = "kernel32.dll";
    40 
    41       [DllImport(KERNEL, CallingConvention = CallingConvention.Winapi)]
    42       public static extern UIntPtr
    43         SetThreadAffinityMask(IntPtr handle, UIntPtr mask);
    44 
    45       [DllImport(KERNEL, CallingConvention = CallingConvention.Winapi)]
    46       public static extern IntPtr GetCurrentThread();       
    47       
    48       private const string LIBC = "libc";
    49       
    50       [DllImport(LIBC)]
    51       public static extern int sched_getaffinity(int pid, IntPtr maskSize,
    52         ref ulong mask);
    53       
    54       [DllImport(LIBC)]
    55       public static extern int sched_setaffinity(int pid, IntPtr maskSize,
    56         ref ulong mask);  
    57     }  
    58   }
    59 }
    60