summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorJaremy Creechley <creechley@gmail.com>2022-03-22 12:08:31 -0700
committerGitHub <noreply@github.com>2022-03-22 20:08:31 +0100
commit4c8934305c48bb52ed0e5a59b47229521cb333ce (patch)
tree2f1243cf33624b85d43bf935228bde0a2aaf6fc6
parentc4a0d4c5e35f09430a1c3d465fc62eb1001b7f9f (diff)
downloadNim-4c8934305c48bb52ed0e5a59b47229521cb333ce.tar.gz
system: thread: stack dealloction on Zephyr (#19633) [backport:1.6]
Try to free the stack allocation when a thread exits. Possibly works for FreeRTOS as well.
-rw-r--r--lib/system/threads.nim18
1 files changed, 16 insertions, 2 deletions
diff --git a/lib/system/threads.nim b/lib/system/threads.nim
index ac727be0a..1c1d1ca1c 100644
--- a/lib/system/threads.nim
+++ b/lib/system/threads.nim
@@ -47,7 +47,10 @@
 when not declared(ThisIsSystem):
   {.error: "You must not import this module explicitly".}
 
-when defined(zephyr) or defined(freertos):
+const
+  hasAllocStack = defined(zephyr) # maybe freertos too?
+
+when hasAllocStack or defined(zephyr) or defined(freertos):
   const
     nimThreadStackSize {.intdefine.} = 8192 
     nimThreadStackGuard {.intdefine.} = 128
@@ -68,6 +71,12 @@ else:
 #const globalsSlot = ThreadVarSlot(0)
 #sysAssert checkSlot.int == globalsSlot.int
 
+# Zephyr doesn't include this properly without some help
+when defined(zephyr):
+  {.emit: """/*INCLUDESECTION*/
+  #include <pthread.h>
+  """.}
+
 # create for the main thread. Note: do not insert this data into the list
 # of all threads; it's not to be stopped etc.
 when not defined(useNimRtl):
@@ -98,6 +107,8 @@ type
     else:
       dataFn: proc (m: TArg) {.nimcall, gcsafe.}
       data: TArg
+    when hasAllocStack:
+      rawStack: pointer
 
 proc `=copy`*[TArg](x: var Thread[TArg], y: Thread[TArg]) {.error.}
 
@@ -161,6 +172,8 @@ else:
       threadTrouble()
     finally:
       afterThreadRuns()
+      when hasAllocStack:
+        deallocShared(thrd.rawStack)
 
 proc threadProcWrapStackFrame[TArg](thrd: ptr Thread[TArg]) {.raises: [].} =
   when defined(boehmgc):
@@ -330,11 +343,12 @@ else:
     when hasSharedHeap: t.core.stackSize = ThreadStackSize
     var a {.noinit.}: Pthread_attr
     doAssert pthread_attr_init(a) == 0
-    when defined(zephyr):
+    when hasAllocStack:
       var
         rawstk = allocShared0(ThreadStackSize + StackGuardSize)
         stk = cast[pointer](cast[uint](rawstk) + StackGuardSize)
       let setstacksizeResult = pthread_attr_setstack(addr a, stk, ThreadStackSize)
+      t.rawStack = rawstk
     else:
       let setstacksizeResult = pthread_attr_setstacksize(a, ThreadStackSize)