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
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
use std::sync::Mutex;
use std::error::Error;
use core::fmt;

pub struct ThreadSafeStruct<T> {
    pub value: Mutex<Option<T>>
}


impl<T> ThreadSafeStruct<T> {
    /// Borrows the value from the mutex, mutably in order to work with/on

    pub fn with(&self, action: impl FnOnce(&mut T)) -> Result<(), ThreadSafeStructError> {
        match self.value.lock() {
            Err(_) => return Err(ThreadSafeStructError { kind: ThreadSafeStructErrorKind::OtherThreadPanickedWithLock }),
            Ok(mut mutex_guard) => {
                match mutex_guard.as_mut() {
                    Some(value) => action(value),
                    None => return Err(ThreadSafeStructError { kind: ThreadSafeStructErrorKind::ValueNotSet })
                }
            }
        }
        Ok(())
    }

    /// Sets the mutex to a value or None

    ///

    /// This provides no guarantee that other threads don't change it straight away

    /// so if you call `with()` after value may have changed

    ///

    /// I.e. two threads, one calls set, the other calls with

    ///    `set` thread wins, and the `with` thread waits for the lock

    ///    as soon as thread `set` finishes, thread `with` will do its thing

    pub fn set(&self, value: Option<T>) {
        let mut mg = self.value.lock().unwrap();
        *mg = value;
    }
}

#[cfg(test)]
mod tests {
    use rayon::prelude::*;
    use lazy_static::*;
    use super::ThreadSafeStruct;

    extern crate test;

    use test::Bencher;
    use std::hint::black_box;
    use crate::ThreadSafeStructErrorKind;


    lazy_static! {
    static ref ERR_TEST: ThreadSafeStruct<i32> = ThreadSafeStruct {
        value: std::sync::Mutex::new(None),
    };}

    #[test]
    fn when_value_is_none_should_return_error() {

        let result = ERR_TEST.with(|_| {});

        assert_eq!(result.is_err(), true);
        assert_eq!(result.unwrap_err().kind, ThreadSafeStructErrorKind::ValueNotSet);
    }


    lazy_static! {
    static ref SET_TEST: ThreadSafeStruct<i32> = ThreadSafeStruct {
        value: std::sync::Mutex::new(None),
    };}

    #[test]
    fn when_setting_value_should_set_value() {

        SET_TEST.set(Some(222));

        let mut fetched_value: i32 = 0;

        SET_TEST.with(|x| {
            fetched_value = *x;
        }).expect("With Faulted!");

        assert_eq!(222, fetched_value);
    }


    lazy_static! {
    static ref ALTER_TEST: ThreadSafeStruct<i32> = ThreadSafeStruct {
        value: std::sync::Mutex::new(Some(222)),
    };}

    #[test]
    fn when_performing_with_should_be_able_to_alter_value() {

        ALTER_TEST.with(|x| {
            *x = *x * 2;
        }).expect("With Faulted!");

        let mut fetched_value: i32 = 0;
        ALTER_TEST.with(|x| {
            fetched_value = *x;
        }).expect("With Faulted!");

        assert_eq!(444, fetched_value);
    }


    lazy_static! {
    static ref THREAD_TEST: ThreadSafeStruct<u32> = ThreadSafeStruct {
        value: std::sync::Mutex::new(Some(0)),
    };}

    const TEST_SIZE: u32 = 100000;

    #[test]
    fn when_threading_should_return_no_errors() {
        let mut vals = <Vec<u8>>::with_capacity(TEST_SIZE as usize);
        unsafe { vals.set_len(TEST_SIZE as usize) }

        // !!!WARNING!!! I DID NOT SET THE VALUES IN `vals`

        // DO NOT TRY READ THEM IN THE THREAD

        vals.par_iter().for_each(|_| {
            THREAD_TEST.with(|i| { *i += 1; }).expect("With Faulted!");
        });
        let mut fetched_value: u32 = 0;
        assert_eq!(THREAD_TEST.with(|x| {
            fetched_value = *x;
        }).is_err(), false);
        assert_eq!(TEST_SIZE, fetched_value);
    }

    lazy_static! {
    static ref THREAD_BENCH_TEST: ThreadSafeStruct<u32> = ThreadSafeStruct {
        value: std::sync::Mutex::new(Some(0)),
    };}

    #[bench]
    fn bench_threaded_model(b: &mut Bencher) {
        b.iter(|| {
            THREAD_BENCH_TEST.set(Some(0));
            THREAD_BENCH_TEST.with(|i| {
                *i += 1;
                if *i % 2 == 1
                {
                    *i += 1;
                }
            }).expect("With Faulted!");
            //std::thread::sleep(Duration::new(0, 1));

        });
        let mut fetched_value: u32 = 0;
        assert_eq!(THREAD_TEST.with(|x| {
            fetched_value = *x;
        }).is_err(), false);
        assert_eq!(0, fetched_value * 0);
    }

    lazy_static! {
    static ref ITER_BENCH_TEST: ThreadSafeStruct<u32> = ThreadSafeStruct {
        value: std::sync::Mutex::new(Some(0)),
    };}

    #[bench]
    fn bench_normal_iterator(b: &mut Bencher) {
        let mut i = 1;
        b.iter(|| {
            i = 0;
            i += 1;
            if i % 2 == 1
            {
                i += 1;
            }
            //std::thread::sleep(Duration::new(0, 1));

        });
        assert_eq!(black_box(2), black_box(i));
    }
}


/// Error stuff

#[derive(Debug)]
pub struct ThreadSafeStructError {
    kind: ThreadSafeStructErrorKind
}

impl fmt::Display for ThreadSafeStructError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.kind {
            ThreadSafeStructErrorKind::OtherThreadPanickedWithLock => write!(f, "Error getting lock, thread with lock panicked"),
            ThreadSafeStructErrorKind::ValueNotSet => write!(f, "Value was not set")
        }
    }
}

// TODO Implement source for debugging

impl Error for ThreadSafeStructError {}

#[derive(Debug)]
#[derive(PartialEq)]
pub enum ThreadSafeStructErrorKind {
    OtherThreadPanickedWithLock,
    ValueNotSet,
}