1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use std::cell::Cell;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::thread;

use crate::order::LOAD_ORDER;
use crate::order::STORE_ORDER;

pub struct ThreadLooper {
    status: Arc<AtomicBool>,
    thread: Cell<Option<thread::JoinHandle<()>>>,
    termination: Arc<AtomicBool>,
}

impl ThreadLooper {
    pub fn new() -> Self {
        let status: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
        let thread: Cell<Option<thread::JoinHandle<()>>> = Cell::new(None);
        let termination: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));

        Self {
            status,
            thread,
            termination,
        }
    }

    pub fn is_active(&self) -> bool {
        self.status.load(LOAD_ORDER)
    }

    pub fn start<F>(&self, function: F)
    where
        F: Fn() -> () + Send + 'static,
    {
        if !self.is_active() {
            self.status.store(true, STORE_ORDER);
            self.termination.store(false, STORE_ORDER);

            let thread: thread::JoinHandle<()> = thread::spawn(self.create(function));
            self.thread.set(Some(thread));
        }
    }

    pub fn terminate(&self) {
        self.termination.store(true, STORE_ORDER);
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

impl ThreadLooper {
    fn create<F>(&self, function: F) -> impl Fn()
    where
        F: Fn() -> () + Send + 'static,
    {
        let status: Arc<AtomicBool> = self.status.clone();
        let termination: Arc<AtomicBool> = self.termination.clone();

        let worker = move || {
            while !termination.load(LOAD_ORDER) {
                function();
            }
            status.store(false, STORE_ORDER);
            termination.store(false, STORE_ORDER);
        };
        worker
    }
}