I’m working in Kotlin/Native. I’d like to create a...
# kotlin-native
j
I’m working in Kotlin/Native. I’d like to create a thread with a non-default stack size because the Mac’s default stack size of 512 KiB isn’t sufficient. As-is, the Crash Reports tab of Console.app is reporting a SIGBUS error on a STACK GUARD field. I believe it’s telling me that my program used more stack than was allocated.
Copy code
Crashed Thread:        5

Exception Type:        EXC_BAD_ACCESS (SIGBUS)
Exception Codes:       KERN_PROTECTION_FAILURE at 0x000000016b0e1120
Exception Codes:       0x0000000000000002, 0x000000016b0e1120

Termination Reason:    Namespace SIGNAL, Code 10 Bus error: 10
Terminating Process:   exc handler [67893]

VM Region Info: 0x16b0e1120 is in 0x16b0e0000-0x16b0e4000;  bytes after start: 4384  bytes before end: 11999
      REGION TYPE                    START - END         [ VSIZE] PRT/MAX SHRMOD  REGION DETAIL
      Stack                       16b058000-16b0e0000    [  544K] rw-/rwx SM=PRV  thread 4
--->  STACK GUARD                 16b0e0000-16b0e4000    [   16K] ---/rwx SM=NUL  ... for thread 5
      Stack                       16b0e4000-16b16c000    [  544K] rw-/rwx SM=PRV  thread 5
(I triggered a similar error by writing a recursive function.) Unfortunately I can’t find build-in APIs to manipulate the stack size of spawned threads.
Worker.start()
accepts a thread name, but nothing like pthread_attr_setstacksize. I also couldn’t find a straightforward way to create a thread without going through the
Worker
API. Any recommendations? Should I open a ticket to request a new API on Worker?
k
Jesse, I know this doesn’t help the stack size issue, but
Worker
is the defacto way to use platform threads in K/N. I was trying to find a different API as well when trying to figure out how to register signal handlers on workers in K/N. I don’t envy the position you’re in!
j
Yeah, though there’s no replacement yet as far as I can see
a
Hi! You can create threads via interop libs, if that suits you. For example, if targeting Apple platforms using NSThread is an option:
Copy code
import platform.Foundation.*
…
    val thread = NSThread {
        println("Hello from the other thread")
        …
    }
    thread.stackSize = …
    thread.start()
…
It's also possible to use
pthreads
but it'll be much less convenient:
Copy code
import kotlinx.cinterop.*
import platform.posix.*
…
    memScoped {
        val thread = alloc<pthread_tVar>()
        val attr = alloc<pthread_attr_t>()
        pthread_attr_init(attr.ptr)
        pthread_attr_setstacksize(attr.ptr, …)
        pthread_create(thread.ptr, attr.ptr, staticCFunction<COpaquePointer?, COpaquePointer?> {
            println("Hello from the other thread")
            …
            null
        }, null)
        pthread_attr_destroy(attr.ptr)
    }
…
(in the code above error handling is omitted completely)