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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
use std::sync::RwLock;
use std::time::{Duration, Instant};
use {Decision, Scale, System};

/// A subset of `System` that can perform work, but my not provide scale. Should
/// be implemented by the user or created by functions such as `func_worker`.
pub trait SystemWork: Sync + Send + 'static {
    /// Per-worker data. See `System::Data`.
    type Data;

    /// Create a new worker. See `System::init`.
    fn init(&self, index: usize) -> Self::Data;

    /// Do a unit of work, and return scheduling information. See `System::work`.
    fn work(&self, data: &mut Self::Data) -> Decision;

    /// Consume a closed worker. See `System::close`.
    fn close(&self, Self::Data) {}
}

impl<T> SystemWork for T
where
    T: System,
{
    type Data = <Self as System>::Data;

    fn init(&self, index: usize) -> Self::Data {
        System::init(self, index)
    }

    fn work(&self, data: &mut Self::Data) -> Decision {
        System::work(self, data)
    }

    fn close(&self, data: Self::Data) {
        System::close(self, data)
    }
}

/// Implementors of this trait are systems with a stored scale.
pub trait SettableSystem: System {
    /// Change the number of active and inactive threads in the system, or shut
    /// the system down.
    fn set_scale(&self, scale: Scale);
}

/// Create a system that has an internally stored pool scale.
pub fn with_scale(sys: impl SystemWork, scale: Scale) -> impl SettableSystem {
    pub struct Sys<W>(W, RwLock<Scale>);

    impl<W: SystemWork> System for Sys<W> {
        type Data = W::Data;

        fn init(&self, index: usize) -> W::Data {
            self.0.init(index)
        }

        fn work(&self, data: &mut W::Data) -> Decision {
            self.0.work(data)
        }

        fn close(&self, data: W::Data) {
            self.0.close(data)
        }

        fn scale(&self) -> Scale {
            *self.1.read().unwrap()
        }
    }

    impl<W: SystemWork> SettableSystem for Sys<W> {
        fn set_scale(&self, scale: Scale) {
            *self.1.write().unwrap() = scale;
        }
    }

    Sys(sys, RwLock::new(scale))
}

/// Create a system that has a set number of active workers.
///
/// ```
/// # extern crate dynpool;
/// # use dynpool::*;
/// # use std::time::{Duration, Instant};
/// # fn main() {
/// // Run 10 threads for 0.5 seconds.
/// let time = Instant::now() + Duration::from_millis(500);
/// let worker = simple_func_worker(|index| println!("Hello from {}", index));
/// let sys = shutdown_after(with_threads(worker, 10), time);
/// Pool::start_fg(sys);
/// # }
pub fn with_threads(w: impl SystemWork, threads: usize) -> impl SettableSystem {
    with_scale(w, Scale::active(threads))
}

/// Begin creating a system which calls the given function from each thread, passing the thread's index.
///
/// ```
/// # extern crate dynpool;
/// # use dynpool::*;
/// # use std::time::{Duration, Instant};
/// # fn main() {
/// // Run 10 threads for 0.5 seconds.
/// let time = Instant::now() + Duration::from_millis(500);
/// let worker = simple_func_worker(|index| println!("Hello from {}", index));
/// let sys = shutdown_after(with_threads(worker, 10), time);
/// Pool::start_fg(sys);
/// # }
pub fn simple_func_worker(func: impl Fn(usize) + Sync + Send + 'static) -> impl SystemWork {
    pub struct Sys<F>(F);

    impl<F: Fn(usize) + Sync + Send + 'static> SystemWork for Sys<F> {
        type Data = usize;

        fn init(&self, index: usize) -> usize {
            index
        }
        fn work(&self, &mut index: &mut usize) -> Decision {
            (self.0)(index);
            Decision::Again
        }
    }

    Sys(func)
}

/// Begin creating a system which calls the given closure to create a work function for each thread.
pub fn func_worker<F>(init: impl Fn(usize) -> F + Sync + Send + 'static) -> impl SystemWork
where
    F: FnMut() -> Decision,
{
    pub struct Sys<F>(F);

    impl<G: FnMut() -> Decision, F: Fn(usize) -> G + Sync + Send + 'static> SystemWork for Sys<F> {
        type Data = G;

        fn init(&self, index: usize) -> G {
            (self.0)(index)
        }
        fn work(&self, func: &mut G) -> Decision {
            func()
        }
    }

    Sys(init)
}

/// Begin creating a system which calls the given closure to create a boxed work function for each thread.
pub fn dyn_func_worker(
    init: impl Fn(usize) -> Box<dyn FnMut() -> Decision> + Sync + Send + 'static,
) -> impl SystemWork {
    type BoxedWorkFn = Box<dyn FnMut() -> Decision>;

    pub struct Sys<F>(F);

    impl<F: Fn(usize) -> BoxedWorkFn + Sync + Send + 'static> SystemWork for Sys<F> {
        type Data = BoxedWorkFn;

        fn init(&self, index: usize) -> BoxedWorkFn {
            (self.0)(index)
        }
        fn work(&self, func: &mut BoxedWorkFn) -> Decision {
            func()
        }
    }

    Sys(init)
}

/// Create a system wrapper which will shutdown after the provided time.
///
/// ```
/// # extern crate dynpool;
/// # use dynpool::*;
/// # use std::time::{Duration, Instant};
/// # fn main() {
/// // Run 10 threads for 0.5 seconds.
/// let time = Instant::now() + Duration::from_millis(500);
/// let worker = simple_func_worker(|index| println!("Hello from {}", index));
/// let sys = shutdown_after(with_threads(worker, 10), time);
/// Pool::start_fg(sys);
/// # }
/// ```
pub fn shutdown_after(sys: impl System, after: Instant) -> impl System {
    pub struct Shutdown<C> {
        after: Instant,
        inner: C,
    }

    impl<C: System + Sync + Send + 'static> System for Shutdown<C> {
        type Data = C::Data;

        fn init(&self, index: usize) -> Self::Data {
            self.inner.init(index)
        }

        fn work(&self, data: &mut Self::Data) -> Decision {
            self.inner.work(data)
        }

        fn close(&self, data: Self::Data) {
            self.inner.close(data)
        }

        fn scale(&self) -> Scale {
            if Instant::now() > self.after {
                Scale::Shutdown
            } else {
                self.inner.scale()
            }
        }
    }

    Shutdown { after, inner: sys }
}

/// Wrap a system so that `System::scale` is called no more than once per period
/// of time, and is otherwise cached. This should be used if scale calculation
/// is expensive.
///
/// ```
/// # extern crate dynpool;
/// # use dynpool::*;
/// # use std::thread::sleep_ms;
/// # use std::time::{Duration, Instant};
/// # fn main() {
/// # let time = Instant::now() + Duration::from_millis(1000);
/// struct Sys;
///
/// impl System for Sys {
///     type Data = ();
///
///     fn init(&self, _: usize) {}
///
///     fn work(&self, _: &mut ()) -> Decision { Decision::Again }
///
///     fn scale(&self) -> Scale {
///         sleep_ms(100); // scale function is slow
///         return Scale::active(10);
///     }
/// }
///
/// let sys = cache_scale(Sys, Duration::from_millis(500));
/// Pool::start_fg(shutdown_after(sys, time));
/// # }
/// ```
pub fn cache_scale(sys: impl System, rate: Duration) -> impl System {
    pub struct Cached<C> {
        scale: RwLock<Option<(Instant, Scale)>>,
        rate: Duration,
        inner: C,
    }

    impl<C: System + Sync + Send + 'static> System for Cached<C> {
        type Data = C::Data;

        fn init(&self, index: usize) -> Self::Data {
            self.inner.init(index)
        }

        fn work(&self, data: &mut Self::Data) -> Decision {
            self.inner.work(data)
        }

        fn close(&self, data: Self::Data) {
            self.inner.close(data)
        }

        fn scale(&self) -> Scale {
            // Is there a better way to do this?
            // Yes. I fixed it for you.

            match &*self.scale.read().unwrap() {
                Some((at, scale)) if at.elapsed() < self.rate => return *scale,
                _ => (),
            }

            match &mut *self.scale.write().unwrap() {
                // in case someone else writes first
                Some((at, scale)) if at.elapsed() < self.rate => return *scale,
                // compute and store new scale
                write => {
                    let scale = self.inner.scale();
                    *write = Some((Instant::now(), scale));
                    scale
                }
            }
        }
    }

    Cached {
        scale: RwLock::new(None),
        rate,
        inner: sys,
    }
}