sp1_core_machine/utils/
concurrency.rs

1use std::sync::{Condvar, Mutex};
2
3/// A turn-based synchronization primitive.
4pub struct TurnBasedSync {
5    pub current_turn: Mutex<usize>,
6    pub cv: Condvar,
7}
8
9impl TurnBasedSync {
10    /// Creates a new [TurnBasedSync].
11    pub fn new() -> Self {
12        TurnBasedSync { current_turn: Mutex::new(0), cv: Condvar::new() }
13    }
14
15    /// Waits for the current turn to be equal to the given turn.
16    pub fn wait_for_turn(&self, my_turn: usize) {
17        let mut turn = self.current_turn.lock().unwrap();
18        while *turn != my_turn {
19            turn = self.cv.wait(turn).unwrap();
20        }
21    }
22
23    /// Advances the current turn.
24    pub fn advance_turn(&self) {
25        let mut turn = self.current_turn.lock().unwrap();
26        *turn += 1;
27        self.cv.notify_all();
28    }
29}