Created
November 8, 2021 21:27
-
-
Save alexxbb/32a0732f77bf526aeb8610ff4b71fd40 to your computer and use it in GitHub Desktop.
An example of mpmc with flume crate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This will spawn 2 producer threads which will try to keep up to NUM_SESSIONS Sessions available for consumers | |
use flume::Receiver; | |
use once_cell::sync::OnceCell; | |
#[derive(Debug, Clone)] | |
struct Session; | |
const NUM_SESSIONS: usize = 10; | |
static POOL: OnceCell<Receiver<Session>> = OnceCell::new(); | |
fn get_session() -> Session { | |
let pool = POOL.get_or_init(|| { | |
let (tx, rx) = flume::bounded(NUM_SESSIONS); | |
for _ in 0..2 { | |
let tx = tx.clone(); | |
std::thread::spawn(move || loop { | |
tx.send(Session).unwrap(); | |
}); | |
} | |
rx | |
}); | |
pool.recv().unwrap() | |
} | |
fn main() { | |
let mut ses = 50; | |
while ses > 0 { | |
let _ = get_session(); | |
println!("Got session {}", ses); | |
ses -= 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment