Skip to main content

comet/internal/
collection_barrier.rs

1use parking_lot::{Condvar, Mutex};
2use std::{cell::Cell, sync::atomic::AtomicBool};
3
4use crate::heap::Heap;
5
6/// This structure stops and resumes all background threads waiting for GC.
7pub struct CollectionBarrier {
8    mutex: Mutex<()>,
9    cv_wakeup: Condvar,
10    collection_requested: AtomicBool,
11    block_for_collection: Cell<bool>,
12    shutdown_requested: Cell<bool>,
13}
14
15impl CollectionBarrier {
16    pub fn new(_heap: *mut Heap) -> Self {
17        Self {
18            mutex: Mutex::new(()),
19            collection_requested: AtomicBool::new(false),
20            cv_wakeup: Condvar::new(),
21            block_for_collection: Cell::new(false),
22            shutdown_requested: Cell::new(false),
23        }
24    }
25
26    pub fn was_gc_requested(&self) -> bool {
27        self.collection_requested.load(atomic::Ordering::Relaxed)
28    }
29    pub fn request_gc(&self) {
30        let guard = self.mutex.lock();
31        let was_already_requested = self
32            .collection_requested
33            .swap(true, atomic::Ordering::AcqRel);
34        let _ = was_already_requested;
35        drop(guard);
36    }
37
38    pub fn notify_shutdown_requested(&self) {
39        let guard = self.mutex.lock();
40        self.shutdown_requested.set(true);
41        self.cv_wakeup.notify_all();
42        drop(guard);
43    }
44    pub fn resume_threads_awaiting_collection(&self) {
45        let guard = self.mutex.lock();
46        self.collection_requested
47            .store(false, atomic::Ordering::Release);
48        self.block_for_collection.set(false);
49        self.cv_wakeup.notify_all();
50        drop(guard);
51    }
52}