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 stackR_CStackLimit- stack size limitR_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:
- The OS still enforces real stack limits
- 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§
- RThread
Builder - Builder for spawning threads with R-appropriate stack sizes.
Constants§
- DEFAULT_
R_ STACK_ SIZE - Default stack size for R-compatible threads (8 MiB).