async_cuda_core/runtime/
work.rs

1/// Represents a unit of work passed to the runtime. Holds a closure inside.
2///
3/// The closure is explictly [`Send`] because it will be sent over the thread boundary to be
4/// executed in the runtime thread. For the same reason, the closure must be `'static`.
5///
6/// # Usage
7///
8/// ```ignore
9/// let work = Work::new(|| {
10///     // ...
11/// });
12/// work.run();
13/// ```
14pub struct Work(Box<dyn FnOnce() + Send + 'static>);
15
16impl Work {
17    /// Create a new work item.
18    ///
19    /// # Arguments
20    ///
21    /// * `f` - Closure to execute.
22    pub fn new(f: impl FnOnce() + Send + 'static) -> Self {
23        Work(Box::new(f))
24    }
25
26    /// Execute work.
27    pub fn run(self) {
28        let Work(f) = self;
29        f();
30    }
31}
32
33#[cfg(test)]
34mod tests {
35    use super::*;
36
37    #[test]
38    fn test_it_runs() {
39        let make_me_true = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
40        let work = Work::new({
41            let make_me_true = make_me_true.clone();
42            move || {
43                make_me_true.store(true, std::sync::atomic::Ordering::Relaxed);
44            }
45        });
46        work.run();
47        assert!(make_me_true.load(std::sync::atomic::Ordering::Relaxed));
48    }
49}