Skip to main content

two_threads/
two_threads.rs

1const N: usize = 8;
2
3fn producer(mut p: fring::Producer<u8, N>) {
4    let mut index = 'a' as u8;
5    for _ in 0..8 {
6        std::thread::sleep(std::time::Duration::from_millis(25));
7        let mut w = p.write(3);
8        for i in 0..w.len() {
9            w[i] = index;
10            index += 1;
11        }
12        println!("write \"{}\"", std::str::from_utf8(&*w).unwrap());
13    }
14}
15
16fn consumer(mut c: fring::Consumer<u8, N>) {
17    loop {
18        std::thread::sleep(std::time::Duration::from_millis(60));
19        let r = c.read(usize::MAX);
20        if r.len() == 0 {
21            // buffer is empty
22            break;
23        }
24        println!("            read \"{}\"", std::str::from_utf8(&*r).unwrap());
25    }
26}
27
28fn main() {
29    let mut b = fring::Buffer::<u8, N>::new();
30    let (p, c) = b.split();
31    std::thread::scope(|s| {
32        s.spawn(|| {
33            producer(p);
34        });
35        consumer(c);
36    });
37}