Compare commits

..

No commits in common. "main" and "step-14" have entirely different histories.

2 changed files with 11 additions and 68 deletions

View file

@ -1,29 +0,0 @@
{
"name": "Rust Workshop",
"image": "mcr.microsoft.com/devcontainers/rust:1-bullseye",
"features": {
"ghcr.io/devcontainers/features/git:1": {}
},
"customizations": {
"vscode": {
"extensions": [
"rust-lang.rust-analyzer",
"vadimcn.vscode-lldb",
"tamasfe.even-better-toml",
"humao.rest-client"
],
"settings": {
"editor.formatOnSave": true,
"rust-analyzer.check.command": "clippy"
}
}
},
"postCreateCommand": "cargo build",
"forwardPorts": [7878],
"portsAttributes": {
"7878": {
"label": "HTTP Server",
"onAutoForward": "notify"
}
}
}

View file

@ -1,31 +1,12 @@
use log::info;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex, mpsc};
use std::{sync, thread};
use std::thread;
static GET: &'static [u8] = b"GET / HTTP/1.1\r\n";
struct Worker {
id: usize,
thread: thread::JoinHandle<()>,
}
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
let thread = thread::spawn(move || {
loop {
let job = receiver.lock().unwrap().recv().unwrap();
job();
}
});
Worker { id, thread }
}
}
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Job>,
threads: Vec<thread::JoinHandle<()>>,
}
impl ThreadPool {
@ -34,35 +15,26 @@ impl ThreadPool {
/// # Panics
///
/// The `new` function panics if the size is zero
pub fn new(size: usize) -> Self {
pub fn new(size: usize) -> Self {
assert!(size > 0);
let mut workers = Vec::with_capacity(size);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)))
let threads = Vec::with_capacity(size);
for _ in 0..size {
}
Self { workers, sender }
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.send(job).unwrap();
Self {threads}
}
}
type Job = Box<dyn FnOnce() + Send + 'static>;
fn main() -> std::io::Result<()> {
env_logger::init();
let listener = TcpListener::bind("127.0.0.1:7878")?;
let pool = ThreadPool::new(4);
for stream in listener.incoming() {
let stream = stream?;
pool.execute(|| handle_connection(stream).unwrap());
thread::spawn(|| {
handle_connection(stream).unwrap();
});
}
Ok(())
}