stoolap_jemalloc/background.rs
1// Copyright 2026 Stoolap Contributors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! A thread that returns free memory to the OS on time. Without it, decay
16//! runs as the allocator is used, so a process that stops allocating keeps
17//! its free pages. It is started explicitly, as in jemalloc, where
18//! background threads are off by default: a library that starts threads
19//! on its own surprises sandboxes, thread counts and forking programs.
20
21use crate::arena;
22use core::sync::atomic::{AtomicBool, Ordering};
23use std::thread;
24
25static RUNNING: AtomicBool = AtomicBool::new(false);
26
27/// Starts the background thread, which ends a decay epoch every 5 seconds
28/// in all arenas, so that pages free for 5 to 10 seconds go back to the OS
29/// even while the process allocates nothing. Returns whether this call
30/// started it; it runs until the process exits.
31///
32/// A child process after `fork` has no such thread and may call this
33/// again.
34///
35/// # Panics
36///
37/// When the OS cannot create a thread.
38pub fn start() -> bool {
39 if RUNNING.swap(true, Ordering::AcqRel) {
40 return false;
41 }
42 let spawned = thread::Builder::new()
43 .name("stoolap-jemalloc-purge".into())
44 .spawn(|| {
45 loop {
46 thread::sleep(arena::DECAY_EPOCH);
47 unsafe { arena::decay_tick() };
48 }
49 });
50 if let Err(e) = spawned {
51 // Not running, so that a later call may try again
52 RUNNING.store(false, Ordering::Release);
53 panic!("spawning the background purge thread: {e}");
54 }
55 true
56}
57
58/// Whether the background thread runs in this process
59pub fn is_running() -> bool {
60 RUNNING.load(Ordering::Acquire)
61}
62
63#[cfg(all(unix, not(miri)))]
64/// In a child after `fork`: the parent's thread did not come along
65pub(crate) fn fork_child() {
66 RUNNING.store(false, Ordering::Release);
67}