use std::thread; use ump_ng::{channel, MsgType}; enum Ops { Die, Add(i32, i32), Sub(i32, i32) } #[test] fn one_at_a_time() { let (server, client) = channel::<(), Ops, i32, ()>(); let server_thread = thread::spawn(move || { let mut croak = false; while !croak { match server.wait().unwrap() { MsgType::Post(()) => panic!("Unexpected Post message"), MsgType::Request(data, rctx) => match data { Ops::Die => { croak = true; rctx.reply(0).unwrap(); } Ops::Add(a, b) => { rctx.reply(a + b).unwrap(); } Ops::Sub(a, b) => { rctx.reply(a - b).unwrap(); } } } } }); let mut a: i32 = 0; let mut b: i32 = 0; for _ in 0..65535 { a += 2; b -= 3; let result = client.req(Ops::Add(a, b)).unwrap(); assert_eq!(result, a + b); } let result = client.req(Ops::Die).unwrap(); assert_eq!(result, 0); server_thread.join().unwrap(); } #[test] fn one_at_a_time_threaded_handler() { let (server, client) = channel::<(), Ops, i32, ()>(); let niterations = 256; let server_thread = thread::spawn(move || { let mut count = 0; let mut handles = Vec::new(); // +1 because we want to wait for the croak message as well while count < niterations + 1 { let MsgType::Request(data, rctx) = server.wait().unwrap() else { panic!("Unexpected message operation type"); }; let h = thread::spawn(move || match data { Ops::Die => { rctx.reply(0).unwrap(); } Ops::Add(a, b) => { rctx.reply(a + b).unwrap(); } Ops::Sub(a, b) => { rctx.reply(a - b).unwrap(); } }); handles.push(h); count += 1; } for h in handles { h.join().unwrap(); } }); let mut a: i32 = 0; let mut b: i32 = 0; for _ in 0..niterations { a += 2; b -= 3; let result = client.req(Ops::Sub(a, b)).unwrap(); assert_eq!(result, a - b); } let result = client.req(Ops::Die).unwrap(); assert_eq!(result, 0); server_thread.join().unwrap(); } // vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :