Skip to main content

Module thread

Module thread 

Source
Expand description

Thread safety utilities for calling R from non-main threads.

R’s stack checking mechanism causes segfaults when R API functions are called from threads other than the main R thread. This module provides utilities to safely disable stack checking when crossing thread boundaries.

§Background

R tracks three variables for stack overflow detection (all non-API):

  • R_CStackStart - top of the main thread’s stack
  • R_CStackLimit - stack size limit
  • R_CStackDir - stack growth direction

When R API functions check the stack, they compare the current stack pointer against these bounds. On a different thread, the stack is completely different, causing false stack overflow detection.

§Solution

Setting R_CStackLimit to usize::MAX disables stack checking entirely. This is safe because:

  1. The OS still enforces real stack limits
  2. R will still function correctly, just without its own overflow detection

§Example

use miniextendr_api::thread::StackCheckGuard;

std::thread::spawn(|| {
    // This would segfault without the guard!
    let _guard = StackCheckGuard::disable();

    // Now safe to call R APIs
    unsafe { miniextendr_api::ffi::Rf_ScalarInteger_unchecked(42) };

    // Guard restores original limit on drop
});

§Feature Gate

This module requires the nonapi feature because it accesses non-API R internals (R_CStackLimit, R_CStackStart, R_CStackDir).

Structs§

RThreadBuilder
Builder for spawning threads with R-appropriate stack sizes.

Constants§

DEFAULT_R_STACK_SIZE
Default stack size for R-compatible threads (8 MiB).