preemptive-threads
A #![no_std]
preemptive multithreading library for Rust, built from scratch for OS kernels and embedded systems.
Features
- No standard library - Built for embedded systems and OS kernels
- Lock-free scheduling - O(1) priority queue with atomic operations
- Thread-safe - No race conditions, proper synchronization
- Priority scheduling - 8 priority levels with round-robin within levels
- Stack protection - Guard pages with canary values and overflow detection
- Static allocation - No heap required, deterministic memory usage
- Safe API - High-level abstractions alongside low-level control
- Platform timers - Cross-platform preemption support (where available)
What's New in v0.1.2
Major architectural improvements:
- Lock-free atomic scheduler replacing unsafe global singleton
- Full CPU context saving including FPU/SSE state
- Signal-safe preemption handler with deferred scheduling
- Enhanced stack protection with guard pages and watermark tracking
- Safe API abstractions - ThreadBuilder, Mutex, ThreadPool
- Platform timer support for cross-platform compatibility
Installation
Add to your Cargo.toml
:
[]
= "0.1.2"
Quick Start
Safe API (Recommended)
use ;
static COUNTER: = new;
Low-Level API
use ;
static mut STACK1: = ;
static mut STACK2: = ;
Protected Stacks
use ;
Platform Timer Integration
use ;
Architecture
Lock-Free Atomic Scheduler
v0.1.2 introduces a completely rewritten scheduler using lock-free atomic operations:
- Per-priority circular buffers for O(1) enqueue/dequeue
- Atomic bitmap for instant highest-priority lookup
- Compare-and-swap operations for thread-safe access
- Exponential backoff for lock acquisition when needed
- Per-CPU scheduling support for future multi-core expansion
Full Context Switching
Context switches now save complete CPU state:
- All general-purpose registers (rax, rbx, rcx, rdx, rsi, rdi, r8-r15)
- Stack and base pointers (rsp, rbp)
- Flags register (rflags) in correct order
- FPU/SSE state via FXSAVE/FXRSTOR instructions
- Future AVX support with runtime CPU feature detection
Enhanced Stack Protection
Multiple layers of stack overflow protection:
- Guard pages filled with canary values
- Bounds checking against stack pointer
- Watermark tracking for high water mark analysis
- Red zone support for x86_64 ABI compliance
- Multiple detection methods for comprehensive coverage
Performance
- Context switching: ~50-100 CPU cycles (depending on FPU state)
- Scheduling: O(1) with priority queues
- Memory overhead: ~64KB per thread (configurable)
- Lock-free operations: No mutex contention in scheduler
- Cache-friendly: Per-CPU local queues for better locality
Platform Support
Platform | Basic Threading | Stack Protection | Hardware Preemption |
---|---|---|---|
Linux x86_64 | ✅ | ✅ | 🚧 Planned |
macOS x86_64 | ✅ | ✅ | 🚧 Planned |
Windows x86_64 | ✅ | ✅ | ❌ |
Other architectures | ❌ | ❌ | ❌ |
Requirements
- Architecture: x86_64 only (ARM64 planned)
- Memory: ~64KB per thread stack (configurable)
- Threads: Maximum 32 concurrent threads
- Rust: 1.70+ (for const generics and advanced features)
Safety
This library provides both safe and unsafe APIs:
Safe API
ThreadBuilder
- Safe thread creation patternsMutex<T>
- RAII mutex with automatic unlockThreadHandle
- Automatic cleanup on dropProtectedStack
- Bounds-checked stack operations
Unsafe API
- Direct scheduler access for maximum performance
- Manual stack management for embedded use cases
- Raw context switching for OS kernel integration
Limitations
- Single-core only (multi-core support planned)
- x86_64 only (ARM64 port in progress)
- Static thread limit (32 threads maximum)
- No thread-local storage (TLS planned)
- Platform-specific preemption (cooperative fallback available)
Examples
See the examples/
directory for complete working examples:
safe_threading.rs
- Safe API demonstrationplatform_timer_demo.rs
- Timer integrationexample.rs
- Basic low-level usagestress_test.rs
- Multi-thread stress testing
Contributing
Contributions welcome! Areas of interest:
- ARM64 architecture support
- Multi-core scheduling
- Platform-specific timer implementations
- Thread-local storage
- Real-time scheduling policies
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT License (LICENSE-MIT)
at your option.