Skip to content

Instantly share code, notes, and snippets.

@kirs
Created May 14, 2020 20:32
Show Gist options
  • Save kirs/3c03354bdbd9046dc1eb68494f43a893 to your computer and use it in GitHub Desktop.
Save kirs/3c03354bdbd9046dc1eb68494f43a893 to your computer and use it in GitHub Desktop.
use futures::stream::StreamExt;
use rand::Rng;
use std::collections::VecDeque;
use std::net::SocketAddr;
use std::thread;
use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::prelude::*;
use tokio::runtime::Runtime;
use tokio::sync::mpsc::channel;
struct Thingy {}
impl Thingy {
// async fn handle(i: usize, sock: tokio::net::TcpStream) {
// println!("handling socket from thread");
// }
fn work(i: usize, mut q: tokio::sync::mpsc::Receiver<tokio::net::TcpStream>) {
let mut rt = Runtime::new().unwrap();
rt.block_on(async {
loop {
match q.recv().await {
Some(_socket) => println!("handling socket from thread, {}", i), // Self::handle(i socket).await,
None => println!("got none!"),
}
}
})
}
}
fn main() {
let mut senders: Vec<tokio::sync::mpsc::Sender<tokio::net::TcpStream>> = Vec::new();
let mut receivers: Vec<tokio::sync::mpsc::Receiver<tokio::net::TcpStream>> = Vec::new();
for _ in 0..4 {
let (s, r) = channel(100);
senders.push(s);
receivers.push(r);
}
// listener thread
thread::spawn(move || {
let mut rt = Runtime::new().unwrap();
rt.block_on(async move {
let addr = "127.0.0.1:6142";
let mut listener = TcpListener::bind(addr).await.unwrap();
let mut rng = rand::thread_rng();
let server = async move {
let mut incoming = listener.incoming();
while let Some(socket_res) = incoming.next().await {
match socket_res {
Ok(socket) => {
// send to random thread
senders[rng.gen_range(0usize, 4usize)]
.send(socket)
.await
.unwrap();
}
Err(err) => {
// Handle error by printing to STDOUT.
println!("accept error = {:?}", err);
}
}
}
};
println!("Server running on localhost:6142");
server.await;
});
});
// handler threads
let mut threads: Vec<thread::JoinHandle<()>> = Vec::new();
let mut i: usize = 0;
for r in receivers.into_iter() {
let handle = thread::spawn(move || {
Thingy::work(i, r);
});
threads.push(handle);
i += 1;
}
threads
.into_iter()
.map(::std::thread::JoinHandle::join)
.collect::<Vec<::std::thread::Result<()>>>();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment