Skip to content

Calling pthread_create with a stack size of 2047 (or at the default) results in an "out of memory" error, but 2048 works #701

@fatlotus

Description

@fatlotus

Here's my example program:

#include <pthread.h>
#include <stdio.h>

void *thread_func(void *arg) {
  printf("The thread is running!\n");
  return NULL;
}

int main() {
  printf("Starting\n");
  pthread_t thread;
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setstacksize(&attr, 2047); // <- 2048 (and above) works, 2047 (and below) does NOT work
  if (pthread_create(&thread, &attr, thread_func, NULL) != 0) {
    perror("pthread_create");
    return 1;
  }
  pthread_join(thread, NULL);
  printf("Done\n");
  return 0;
}

Here's main.c as a WAT file: main.wat.txt

I'm compiling and running with the following commands:

# With a stack size of 2048 or greater
$ /opt/homebrew/opt/llvm/bin/clang -Wl,--import-memory,--export-memory -g --target=wasm32-wasip1-threads --sysroot=~/Downloads/wasi-sdk-29.0-arm64-macos/share/wasi-sysroot main.c -o main.wasm
$ wasmtime run --wasi threads=y --wasm threads=y main.wasm
Starting
The thread is running!
Done

# With a stack size of 2047 or less
$ /opt/homebrew/opt/llvm/bin/clang -Wl,--import-memory,--export-memory -g --target=wasm32-wasip1-threads --sysroot=~/Downloads/wasi-sdk-29.0-arm64-macos/share/wasi-sysroot main.c -o main.wasm
$ wasmtime run --wasi threads=y --wasm threads=y main.wasm
Starting
pthread_create: Out of memory

It also fails if you leave the stack size as the default.

Platform: I'm using an macOS 14.6.1 on an M1, with Homebrew Clang, a pre-built WASI sysroot, and wasm32-wasip1-threads, though it also repros with wasm32-wasi-threads.

Looking through the code, I see a PTHREAD_STACK_MIN config variable set to 2048 which.. would seem to explain this behavior, though I can't find any place outside of pthread_attr_setstack where it ever gets read. It also seems strange that the default behavior of pthread would result in a stack that's too small.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions