go_lib/lib.rs
1// SPDX-License-Identifier: Apache-2.0
2//! # go-lib
3//!
4//! Go-style concurrency for Rust: goroutines, channels, `select`, `WaitGroup` —
5//! built on a port of the M:N scheduler from <https://github.com/golang/go>.
6//!
7//! No async runtime is used: the scheduler, channels, and parking primitives
8//! are ported from `src/runtime/` in the Go repo. Mutexes and read-write locks
9//! are taken straight from [`std::sync`] because their uncontended path is
10//! just an atomic CAS — porting Go's versions would be code without benefit.
11//! See [`runtime::syscall`] for the shim that keeps `std` blocking calls
12//! scheduler-safe.
13//!
14//! ## Public surface
15//! - `go!` / `select!` macros — spawn goroutines, multiplex channel ops
16//! - [`chan`] — buffered and unbuffered channels
17//! - [`net`] — goroutine-aware `TcpListener` / `TcpStream` *(v0.2.0)*
18//! - [`sync::WaitGroup`] — wait for a collection of goroutines
19//! - [`sync::Cond`] — goroutine-aware condition variable
20//! - [`sync::Mutex`] / [`sync::RwLock`] — re-exports of `std::sync`
21//! - [`context`] — cancellation and deadline propagation
22//! - [`set_panic_handler`] — customise goroutine-panic behaviour
23//! - [`set_gomaxprocs`] / [`gomaxprocs`] — runtime parallelism control
24//!
25//! ## Internals
26//! See [`runtime`] for the scheduler (G/M/P, parking, work stealing, sysmon,
27//! stack growth, async preemption, netpoll).
28//!
29//! ## v0.3.1 — new in this release
30//!
31//! - **G state machine**: `casgstatus` centralises all goroutine status
32//! transitions. `GSYSCALL`, `GCOPYSTACK`, `GPREEMPTED`, and `GSCAN` are
33//! now wired into `entersyscall`/`exitsyscall`, `copystack`, and `preemptm`
34//! respectively, matching Go 1.14+ semantics.
35//! - **`systemstack`**: runs a closure on the M's g0 (system) stack via a
36//! naked-assembly RSP/SP switch. Implemented for both AMD64 (SysV + Windows
37//! x64) and AArch64 (AAPCS64).
38//!
39//! ## v0.2.0 — new in this release
40//!
41//! - **Dynamic stack growth** (Step 3): goroutines start with a 64 KiB stack
42//! and grow automatically up to 1 GiB via SIGSEGV guard-page detection and
43//! `copystack` (conservative pointer adjustment).
44//! - **Async preemption** (Step 4): sysmon sends `SIGURG` to the M thread whose
45//! goroutine has run > 10 ms. The signal handler redirects execution to an
46//! assembly trampoline that saves all registers, calls `async_preempt2`, and
47//! restores state on resume — a transparent, non-cooperative yield.
48//! - **Netpoll / async I/O** (Step 5): `epoll` on Linux, `kqueue` on macOS,
49//! IOCP on Windows. Goroutines park on blocking I/O and are re-enqueued
50//! when the operation is ready (Unix) or completes (Windows IOCP).
51//! See the [`net`] module for `TcpListener` / `TcpStream`.
52//!
53//! ## Known limitations
54//!
55//! ### `defer` / `recover` / cross-goroutine `panic`
56//! Goroutine panics are caught and routed to [`set_panic_handler`]; the
57//! process does not abort. Go's `recover()` (stopping panic propagation at a
58//! call-stack boundary) has no direct Rust equivalent — use `catch_unwind`
59//! inside the goroutine body when fine-grained recovery is needed.
60//!
61//! ### Race detector
62//! The Go race detector is a compiler/runtime feature with no Rust equivalent
63//! in this crate. Use `cargo test --cfg loom` with the [loom model checker]
64//! for systematic concurrency testing.
65//!
66//! ## Unsafe conventions
67//! The runtime modules (`src/runtime/`) are a direct port of Go's C-adjacent
68//! runtime code. Almost every function is `unsafe fn` because it operates on
69//! raw goroutine pointers and `mmap`'d memory. Inner `unsafe {}` blocks are
70//! omitted for brevity (suppressed via `unsafe_op_in_unsafe_fn`) — the caller's
71//! obligation is documented in each function's `# Safety` section instead.
72#![deny(missing_docs)]
73// The runtime is a deliberate port of Go's low-level C-adjacent scheduler code.
74// Virtually every function is `unsafe fn`; requiring inner `unsafe {}` blocks
75// on every raw-pointer dereference would add noise without safety information.
76// Each `unsafe fn`'s contract is documented in its `# Safety` section instead.
77#![allow(unsafe_op_in_unsafe_fn)]
78
79pub mod chan;
80pub mod context;
81/// Goroutine-aware TCP networking (Step 5: netpoll integration).
82///
83/// See [`net::TcpListener`] and [`net::TcpStream`].
84///
85/// On Linux and macOS the backend is `epoll` / `kqueue` (readiness-based).
86/// On Windows the backend is I/O Completion Ports (IOCP): overlapped
87/// `WSARecv`/`WSASend` operations are issued and the goroutine parks until
88/// `GetQueuedCompletionStatusEx` signals completion.
89#[cfg(not(windows))]
90pub mod net;
91#[cfg(windows)]
92#[path = "net_windows.rs"]
93pub mod net;
94pub mod runtime;
95pub mod select;
96pub mod sync;
97
98mod go_macro;
99pub(crate) mod loom_shim;
100
101/// Initialise the go-lib scheduler and run `f` as the first goroutine.
102///
103/// Blocks the calling thread until `f` returns. The scheduler threads
104/// (one per logical CPU) continue running in the background after `run`
105/// returns; they park themselves when there is no more work.
106///
107/// # Example
108///
109/// ```no_run
110/// go_lib::run(|| {
111/// println!("hello from a goroutine");
112/// });
113/// ```
114pub fn run<F: FnOnce() + Send + 'static>(f: F) {
115 runtime::sched::run_impl(f);
116}
117
118/// Yield the CPU, giving other goroutines a chance to run.
119///
120/// Moves the current goroutine to the back of the global run queue and
121/// re-enters the scheduler. Execution resumes at the next `gosched()` call
122/// site once the goroutine is rescheduled.
123///
124/// CPU-bound loops should call `gosched()` periodically. The background
125/// sysmon thread also sets a preemption hint after 10 ms, but because v1 has
126/// no stack-check traps the goroutine must call `gosched()` voluntarily for
127/// the hint to take effect.
128///
129/// # Panics
130///
131/// Panics if called from outside a goroutine (e.g. from `main` before
132/// calling [`run`]).
133///
134/// # Example
135///
136/// ```no_run
137/// go_lib::run(|| {
138/// for i in 0..1_000_000 {
139/// if i % 10_000 == 0 {
140/// go_lib::gosched(); // let other goroutines run
141/// }
142/// }
143/// });
144/// ```
145pub fn gosched() {
146 // SAFETY: we are on a goroutine stack (enforced by the debug_assert inside
147 // the internal gosched that current_g() is non-null).
148 unsafe { runtime::sched::gosched() }
149}
150
151/// Wrap a potentially-blocking operation so the go-lib scheduler can
152/// hand off this goroutine's P to another M while the OS thread is in the
153/// kernel.
154///
155/// Calls [`entersyscall`][runtime::syscall::entersyscall] before `f` and
156/// [`exitsyscall`][runtime::syscall::exitsyscall] after `f` returns. This is
157/// a no-op when called outside the scheduler (before [`run`]).
158///
159/// # Example
160///
161/// ```no_run
162/// go_lib::run(|| {
163/// let data = go_lib::with_syscall(|| std::fs::read("file.txt"));
164/// });
165/// ```
166pub fn with_syscall<F, R>(f: F) -> R
167where
168 F: FnOnce() -> R,
169{
170 runtime::syscall::with_syscall(f)
171}
172
173/// Sleep the current goroutine for at least `d`.
174///
175/// Parks the goroutine and lets other goroutines run; the background timer
176/// thread calls [`goready`][runtime::park] when the duration elapses.
177///
178/// Passing `Duration::ZERO` yields to the scheduler without sleeping.
179///
180/// # Panics
181///
182/// Debug-panics if called from outside a goroutine.
183///
184/// # Example
185///
186/// ```no_run
187/// go_lib::run(|| {
188/// go_lib::sleep(std::time::Duration::from_millis(10));
189/// });
190/// ```
191pub fn sleep(d: std::time::Duration) {
192 // SAFETY: called from a goroutine context (checked by debug_assert in sleep).
193 unsafe { runtime::time::goroutine_sleep(d) }
194}
195
196/// Spawn a goroutine. Called by the [`go!`] macro; not for direct use.
197///
198/// Must be called from within a running goroutine (i.e. inside [`run`]).
199///
200/// # Panics
201///
202/// Debug-panics if called from outside a goroutine context.
203#[doc(hidden)]
204pub fn __spawn<F: FnOnce() + Send + 'static>(f: F) {
205 runtime::sched::spawn_goroutine(f)
206}
207
208// ---------------------------------------------------------------------------
209// GOMAXPROCS
210// ---------------------------------------------------------------------------
211
212/// Return the current number of logical processors (GOMAXPROCS).
213///
214/// This equals the value set by the `GOMAXPROCS` environment variable at
215/// startup, or [`set_gomaxprocs`], or `available_parallelism` if neither was
216/// provided.
217pub fn gomaxprocs() -> usize {
218 runtime::sched::gomaxprocs()
219}
220
221/// Set the number of logical processors and return the previous value.
222///
223/// See [`runtime::sched::set_gomaxprocs`] for full semantics.
224///
225/// # Example
226///
227/// ```no_run
228/// let old = go_lib::set_gomaxprocs(2);
229/// println!("was {old}, now {}", go_lib::gomaxprocs());
230/// ```
231pub fn set_gomaxprocs(n: usize) -> usize {
232 runtime::sched::set_gomaxprocs(n)
233}
234
235// ---------------------------------------------------------------------------
236// Goroutine panic handler
237// ---------------------------------------------------------------------------
238
239/// Register a custom handler for goroutine panics.
240///
241/// By default, a panicking goroutine prints its payload to stderr and the
242/// scheduler continues running other goroutines — the process does **not**
243/// abort.
244///
245/// Calling `set_panic_handler` replaces the previous handler. The handler
246/// receives the `Box<dyn Any + Send>` payload from `std::panic::catch_unwind`.
247///
248/// # Example
249///
250/// ```no_run
251/// go_lib::set_panic_handler(|payload| {
252/// if let Some(s) = payload.downcast_ref::<String>() {
253/// eprintln!("goroutine panicked: {s}");
254/// }
255/// });
256/// ```
257pub fn set_panic_handler<F>(f: F)
258where
259 F: Fn(Box<dyn std::any::Any + Send + 'static>) + Send + Sync + 'static,
260{
261 runtime::sched::set_panic_handler(f);
262}