Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

affinity_posix should get this patch (for Android/Termux) #172

Open
HJarausch opened this issue Apr 7, 2021 · 0 comments
Open

affinity_posix should get this patch (for Android/Termux) #172

HJarausch opened this issue Apr 7, 2021 · 0 comments

Comments

@HJarausch
Copy link

I have adapted a recent patch to threadlocalstorage.nim from Nim-Devel to affinity_posix.nim.
Please apply the following patch to affinity_posix.nim.

--- affinity_posix.nim.ORIG	2021-04-07 15:15:30.550835730 +0200
+++ affinity_posix.nim	2021-04-07 16:51:07.136049648 +0200
@@ -35,17 +35,31 @@
 # Nim doesn't allow the main thread to set its own affinity
 
 proc set_thread_affinity(t: Pthread, cpu: int32) {.inline.}=
-  when defined(osx) or defined(android):
+  when defined(osx):
     {.warning: "To improve performance we should pin threads to cores.\n" &
-                "This is not possible with MacOS or Android.".}
-    # Note: on Android it's even more complex due to the Big.Little architecture
-    #       with cores with different performance profiles to save on battery
-  else:
+                "This is not possible with MacOS.".}
+  else :
     var cpuset {.noinit.}: CpuSet
 
     cpu_zero(cpuset)
     cpu_set(cpu, cpuset)
-    pthread_setaffinity_np(t, sizeof(CpuSet), cpuset)
+  
+    if  defined(android) :
+      # libc of android doesn't implement pthread_setaffinity_np,
+      # it exposes pthread_gettid_np though, so we can use that in combination
+      # with sched_setaffinity to set the thread affinity.
+      type Pid {.importc: "pid_t", header: "<sys/types.h>".} = int32 # From posix_other.nim
+
+      proc setAffinityTID(tid: Pid; setsize: csize_t; s: var CpuSet) {.
+        importc: "sched_setaffinity", header: "<sched.h>".}
+
+      proc pthread_gettid_np(thread: Pthread): Pid {.
+        importc: "pthread_gettid_np", header: "<pthread.h>".}
+
+      setAffinityTID(pthread_gettid_np(t), csize_t(sizeof(CpuSet)), cpuset)
+
+    else:
+      pthread_setaffinity_np(t, sizeof(CpuSet), cpuset)
 
 proc pinToCpu*(cpu: int32) {.inline.} =
   ## Set the affinity of the main thread (the calling thread)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant