Created
April 16, 2024 03:32
-
-
Save eval-exec/6fc79b966620cc45b00e8a05f02e88f4 to your computer and use it in GitHub Desktop.
This file contains 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
// 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() | |
} | |
} | |
type ProcessBlockRequest = Request<usize, 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: usize) { | |
Request::call(&self.process_block_sender, b); | |
} | |
} | |
fn main() { | |
let chain_controller = chain_service(); | |
chain_controller.process_block(1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment