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
//! Concrete implementations of shared counter using counting networks implenented in this crate.

use std::cell::Cell;

use networks::BitonicNetwork;

struct CountingBucket {
    value: Cell<usize>,
}

impl CountingBucket {
    fn new(starting_value: usize) -> Self {
        CountingBucket {
            value: Cell::new(starting_value),
        }
    }

    fn get(&self) -> usize {
        self.value.get()
    }

    fn inc(&self, increment: usize) {
        self.value.set(self.value.get() + increment);
    }
}

/// Output sequential values without duplicates or skips.
pub trait Counter {
    /// Retrieve value from counter and update internal state.
    fn next(&self) -> usize;
}

/// Concrete counter based on [BitonicNetwork](super::networks::BitonicNetwork).
pub struct BitonicCountingNetwork(BitonicNetwork<CountingBucket>);

impl BitonicCountingNetwork {
    /// Create a new counter with specified width.
    ///
    /// Choice of width will not effect output of the counter, but higher values will ensure
    /// less contention among threads while accessing the counter at the cost of more memory.
    ///
    /// # Examples
    ///
    /// ```
    /// use counting_networks::counters::{Counter, BitonicCountingNetwork};
    ///
    /// let counter = BitonicCountingNetwork::new(8);
    /// 
    /// assert_eq!(counter.next(), 0);
    /// ```
    pub fn new(width: usize) -> Self {
        let outputs = (0..width)
            .map(|v| CountingBucket::new(v))
            .collect::<Vec<_>>();
        BitonicCountingNetwork(BitonicNetwork::new(outputs))
    }

    /// Returns the output width of the internal bitonic network.
    ///
    /// # Examples
    ///
    /// ```
    /// use counting_networks::counters::BitonicCountingNetwork;
    ///
    /// let counter = BitonicCountingNetwork::new(8);
    /// 
    /// assert_eq!(counter.width(), 8);
    /// ```
    pub fn width(&self) -> usize {
        self.0.width()
    }
}

impl Counter for BitonicCountingNetwork {
    fn next(&self) -> usize {
        let bucket = self.0.traverse();

        let output = bucket.get();
        bucket.inc(self.width());

        output
    }
}

#[cfg(test)]
mod tests {

    use std::sync::Arc;
    use std::thread;

    use super::*;

    #[test]
    fn create_counter() {
        const WIDTH: usize = 16;
        let counter = BitonicCountingNetwork::new(WIDTH);

        assert_eq!(counter.width(), WIDTH);
    }

    fn sync_only<T: Sync>(_: T) {}
    fn send_only<T: Send>(_: T) {}

    #[test]
    fn is_send() {
        send_only(BitonicCountingNetwork::new(4));
    }

    #[test]
    fn is_sync() {
        sync_only(BitonicCountingNetwork::new(4));
    }

    #[test]
    fn concurrent_counting() {
        const WIDTH: usize = 8;
        const NUM_THREADS: usize = 8;
        const NUM_COUNTS: usize = 4;

        let counter = Arc::new(BitonicCountingNetwork::new(WIDTH));
        let mut thread_handles = Vec::new();
        for _ in 0..NUM_THREADS {
            let counter_copy = counter.clone();
            let handle = thread::spawn(move || {
                let mut values = Vec::new();
                for _ in 0..NUM_COUNTS {
                    let value = counter_copy.next();
                    values.push(value)
                }
                values
            });

            thread_handles.push(handle);
        }

        let mut results: Vec<usize> = thread_handles.into_iter().fold(
            Vec::new(),
            |mut container, handle| {
                container.extend(handle.join().unwrap());

                container
            },
        );
        results.sort();
        assert_eq!(results, (0..(NUM_THREADS * NUM_COUNTS)).collect::<Vec<_>>());
    }

}