From 4660ab927cebf7c900fb57ec5d4e2c2e341a1ea9 Mon Sep 17 00:00:00 2001 From: Natalya McKay Date: Sun, 25 May 2025 00:31:44 -0400 Subject: [PATCH] Implement setThreadAffinity for Linux. --- .../cortex/voxy/common/util/ThreadUtils.java | 27 +++++++++++++++++++ .../voxy/common/util/cpu/CpuLayout.java | 12 +++++++-- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/main/java/me/cortex/voxy/common/util/ThreadUtils.java b/src/main/java/me/cortex/voxy/common/util/ThreadUtils.java index 4db33e7a..34f80835 100644 --- a/src/main/java/me/cortex/voxy/common/util/ThreadUtils.java +++ b/src/main/java/me/cortex/voxy/common/util/ThreadUtils.java @@ -5,6 +5,7 @@ import org.lwjgl.system.MemoryStack; import org.lwjgl.system.MemoryUtil; import org.lwjgl.system.Platform; import org.lwjgl.system.windows.Kernel32; +import org.lwjgl.system.APIUtil; //Platform specific code to assist in thread utilities public class ThreadUtils { @@ -15,6 +16,7 @@ public class ThreadUtils { private static final boolean isWindows = Platform.get() == Platform.WINDOWS; private static final long SetThreadPriority; private static final long SetThreadSelectedCpuSetMasks; + private static final long schedSetaffinity; static { if (isWindows) { SetThreadPriority = Kernel32.getLibrary().getFunctionAddress("SetThreadPriority"); @@ -23,6 +25,13 @@ public class ThreadUtils { SetThreadPriority = 0; SetThreadSelectedCpuSetMasks = 0; } + + if (Platform.get() == Platform.LINUX) { + var libc = APIUtil.apiCreateLibrary("libc.so.6"); + schedSetaffinity = APIUtil.apiGetFunctionAddress(libc, "sched_setaffinity"); + } else { + schedSetaffinity = 0; + } } public static boolean SetThreadSelectedCpuSetMasksWin32(long mask) { @@ -70,4 +79,22 @@ public class ThreadUtils { } return true; } + + public static boolean schedSetaffinityLinux(long masks[]) { + if (schedSetaffinity == 0 || isWindows) { + return false; + } + try (var stack = MemoryStack.stackPush()) { + long ptr = stack.ncalloc(8, masks.length, 8); + for (int i=0; i a.group - b.group); + long[] msks = new long[affinities.length]; + for (int i=0; i