Skip to content

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

Open
@HJarausch

Description

@HJarausch

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions