-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspmc_w_mutex.rs
More file actions
45 lines (40 loc) · 1.4 KB
/
spmc_w_mutex.rs
File metadata and controls
45 lines (40 loc) · 1.4 KB
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
//! Write from multiple threads, read from multiple threads using spmc::Queue with mutex.
//!
//! This is faster than mpmc version, when "writers" do not write simultaneously.
use std::sync::Arc;
use chute::LendingReader;
fn main() {
const WRITERS : usize = 4;
const WRITER_MESSAGES : usize = 100;
const MESSAGES : usize = WRITERS*WRITER_MESSAGES;
const READERS : usize = 4;
let queue: Arc<spin::Mutex<chute::spmc::Queue<_>>> = Default::default();
std::thread::scope(|s| {
// READ threads
for _ in 0..READERS {
let mut reader = queue.lock().reader();
s.spawn(move || {
let mut sum = 0;
for _ in 0..MESSAGES {
// Wait for the next message.
let msg = loop {
if let Some(msg) = reader.next() {
break msg;
}
};
sum += msg;
}
assert_eq!(sum, (0..MESSAGES).sum());
});
}
// WRITE threads
for t in 0..WRITERS {
let queue = queue.clone();
s.spawn(move || {
for i in 0..WRITER_MESSAGES {
queue.lock().push(t*WRITER_MESSAGES + i);
}
});
}
});
}