Skip to content

Instantly share code, notes, and snippets.

@eval-exec
Created April 16, 2024 03:34
Show Gist options
  • Save eval-exec/3444a4dc1a51a052a8555c3f3673f351 to your computer and use it in GitHub Desktop.
Save eval-exec/3444a4dc1a51a052a8555c3f3673f351 to your computer and use it in GitHub Desktop.
// snippet of code @ 2024-04-16 10:58:15
// === Rust Playground ===
// This snippet is in: /tmp/rust-playground/at-2024-04-16-105815/
use crossbeam_channel::{after, Sender};
use std::{io::Error, sync::mpsc};
// Execute the snippet: C-c C-c
// Delete the snippet completely: C-c k
// Toggle between main.rs and Cargo.toml: C-c b
/// Synchronous request sent to the service.
pub struct Request<A, R> {
/// One shot channel for the service to send back the response.
pub responder: mpsc::Sender<R>,
/// Request arguments.
pub arguments: A,
}
impl<A, R> Request<A, R> {
/// Call the service with the arguments and wait for the response.
pub fn call(sender: &Sender<Request<A, R>>, arguments: A) -> Option<R> {
let (responder, response) = mpsc::channel();
let _ = sender.send(Request {
responder,
arguments,
});
response.recv().ok()
}
}
#[derive(Debug)]
struct Block {
b: usize,
}
impl Drop for Block {
fn drop(&mut self) {
println!("dropping block {}", self.b);
}
}
type ProcessBlockRequest = Request<Block, Result<(), Error>>;
use crossbeam_channel::select;
struct ChainController {
process_block_sender: Sender<ProcessBlockRequest>,
}
fn chain_service() -> ChainController {
let (ct, cx) = crossbeam_channel::bounded::<ProcessBlockRequest>(10);
std::thread::spawn(move || {
let timeout = std::time::Duration::from_secs(3);
return;
select! {
recv(cx) -> msg => match msg {
Ok(Request{responder, arguments: s}) => {
println!("got a request {:?}",s);
},
_ => {
println!("error");
}
},
recv(after(timeout)) -> _ => println!("timed out")
}
});
ChainController {
process_block_sender: ct,
}
}
impl ChainController {
fn process_block(&self, b: Block) {
Request::call(&self.process_block_sender, b);
}
}
fn main() {
let chain_controller = chain_service();
chain_controller.process_block(Block { b: 1 });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment