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
use std::sync::{Arc, Mutex};

use sync42::wait_list::WaitList;

//////////////////////////////////////////// biometrics ////////////////////////////////////////////

static HEAD_PASSBACK_INITIATED: biometrics::Counter =
    biometrics::Counter::new("playground.clicker.head_passback_initiated");
static HEAD_PASSBACK_FINISHED: biometrics::Counter =
    biometrics::Counter::new("playground.clicker.head_passback_finished");
static INCREMENT_OUTSTANDING_CALLS: biometrics::Counter =
    biometrics::Counter::new("playground.clicker.increment_outstanding_calls");
static DECREMENT_OUTSTANDING_CALLS: biometrics::Counter =
    biometrics::Counter::new("playground.clicker.decrement_outstanding_calls");
static BLOCKING_ON_TICKET_ACQUISITION: biometrics::Counter =
    biometrics::Counter::new("playground.clicker.blocking_on_ticket_acquisition");
static ABLE_TO_ACQUIRE_TICKETS: biometrics::Counter =
    biometrics::Counter::new("playground.clicker.able_to_acquire_tickets");

pub fn register_biometrics(collector: &mut biometrics::Collector) {
    sync42::register_biometrics(collector);
    collector.register_counter(&HEAD_PASSBACK_INITIATED);
    collector.register_counter(&HEAD_PASSBACK_FINISHED);
    collector.register_counter(&INCREMENT_OUTSTANDING_CALLS);
    collector.register_counter(&DECREMENT_OUTSTANDING_CALLS);
    collector.register_counter(&BLOCKING_ON_TICKET_ACQUISITION);
    collector.register_counter(&ABLE_TO_ACQUIRE_TICKETS);
}

////////////////////////////////////////////// Counter /////////////////////////////////////////////

struct Counter {
    count: Mutex<u64>,
}

impl Counter {
    const fn new() -> Self {
        Self {
            count: Mutex::new(1),
        }
    }

    fn count(&self, amount: u64) -> u64 {
        let mut count = self.count.lock().unwrap();
        let alloc: u64 = *count;
        *count = count.wrapping_add(amount);
        std::thread::sleep(std::time::Duration::from_millis(1_000));
        alloc
    }
}

////////////////////////////////////////////// Clicker /////////////////////////////////////////////

#[derive(Clone, Debug, Default)]
enum WaitState {
    #[default]
    Present,
    CallingCount,
    Counted(u64),
}

struct ClickerState {
    outstanding_calls: u64,
    head_passback: bool,
}

impl ClickerState {
    const fn new() -> Self {
        Self {
            outstanding_calls: 0,
            head_passback: false,
        }
    }
}

struct Clicker<'a> {
    concurrent_count_calls: u64,
    counter: &'a Counter,
    state: Mutex<ClickerState>,
    wait_list: WaitList<WaitState>,
}

impl<'a> Clicker<'a> {
    fn new(concurrent_count_calls: u64, counter: &'a Counter) -> Self {
        Self {
            concurrent_count_calls,
            counter,
            state: Mutex::new(ClickerState::new()),
            wait_list: WaitList::new(),
        }
    }

    fn click(&self) -> u64 {
        let mut waiter = self.wait_list.link(WaitState::Present);
        let tickets = {
            let mut state = self.state.lock().unwrap();
            'conditions: while !(state.outstanding_calls < self.concurrent_count_calls)
                && !(waiter.is_head() && state.head_passback)
            {
                match waiter.load() {
                    Some(WaitState::Present) => {
                        BLOCKING_ON_TICKET_ACQUISITION.click();
                        state = waiter.naked_wait(state);
                    }
                    Some(WaitState::CallingCount) => {
                        panic!("CallingCount state achieved before allowed to call count");
                    }
                    Some(WaitState::Counted(_)) => {
                        break 'conditions;
                    }
                    None => {
                        panic!("Our waiter was initialized to WaitState::Present, but the value got lost");
                    }
                }
                if state.outstanding_calls < self.concurrent_count_calls && !state.head_passback{
                    HEAD_PASSBACK_INITIATED.click();
                    state.head_passback = true;
                    INCREMENT_OUTSTANDING_CALLS.click();
                    state.outstanding_calls += 1;
                    self.wait_list.notify_head();
                }
            }
            if let Some(WaitState::Counted(x)) = waiter.load() {
                self.wait_list.unlink(waiter);
                self.wait_list.notify_head();
                return x;
            }
            ABLE_TO_ACQUIRE_TICKETS.click();
            let mut count = 0;
            for mut w in waiter.iter() {
                match w.load() {
                    Some(WaitState::Present) => {
                        count += 1;
                    }
                    Some(WaitState::CallingCount) | Some(WaitState::Counted(_)) => {
                        break;
                    }
                    None => {
                        panic!("Our waiter was initialized to WaitState::Present, but the value got lost");
                    }
                };
            }
            waiter.store(WaitState::CallingCount);
            if waiter.is_head() && state.head_passback {
                HEAD_PASSBACK_FINISHED.click();
                state.head_passback = false;
            } else {
                INCREMENT_OUTSTANDING_CALLS.click();
                state.outstanding_calls += 1;
            }
            count
        };
        let ticket_run_start = self.counter.count(tickets);
        for (mut w, ticket) in
            std::iter::zip(waiter.iter(), ticket_run_start..ticket_run_start + tickets)
        {
            w.store(WaitState::Counted(ticket))
        }
        if let Some(WaitState::Counted(x)) = waiter.load() {
            self.wait_list.unlink(waiter);
            {
                let mut state = self.state.lock().unwrap();
                if !state.head_passback {
                    HEAD_PASSBACK_INITIATED.click();
                    state.head_passback = true;
                } else {
                    state.outstanding_calls -= 1;
                    DECREMENT_OUTSTANDING_CALLS.click();
                }
            }
            self.wait_list.notify_head();
            return x;
        }
        panic!("We gave everyone except ourselves a ticket.");
    }
}

/////////////////////////////////////////////// main ///////////////////////////////////////////////

fn main() {
    // Setup the environment.
    std::thread::spawn(|| {
        let mut collector = biometrics::Collector::new();
        register_biometrics(&mut collector);
        let fout = std::fs::File::create("/dev/stdout").unwrap();
        let mut emit = biometrics::PlainTextEmitter::new(fout);
        loop {
            if let Err(e) = collector.emit(&mut emit) {
                eprintln!("collector error: {}", e);
            }
            std::thread::sleep(std::time::Duration::from_millis(250));
        }
    });
    // Configure the experiment.
    const NUMBER_OF_THREADS: u64 = sync42::MAX_CONCURRENCY as u64 / 2;
    const CONCURRENT_COUNT: u64 = 1;
    // Setup the experiment.
    static COUNTER: Counter = Counter::new();
    let clicker: Arc<Clicker> = Arc::new(Clicker::new(CONCURRENT_COUNT, &COUNTER));
    // Spawn all threads.
    let mut threads = Vec::new();
    for _ in 0..NUMBER_OF_THREADS {
        let c = Arc::clone(&clicker);
        threads.push(std::thread::spawn(move || loop {
            let ticket = c.click();
            println!("{}", ticket);
            if ticket > 1_000_000 {
                break;
            }
        }));
    }
    // Join all threads.
    for thread in threads.into_iter() {
        thread.join().unwrap();
    }
}