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