multithreading

This commit is contained in:
v 2023-12-28 12:47:17 +01:00
parent ab847d4ea0
commit b130138c2b

View file

@ -5,6 +5,7 @@ use std::error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::net::TcpStream;
use std::thread;
fn main() -> Result<(), Box<dyn Error>> {
let decoder = Decoder::new(File::open("nopslide.png")?);
@ -12,41 +13,52 @@ fn main() -> Result<(), Box<dyn Error>> {
let mut pixelbuf = vec![0; reader.output_buffer_size()];
let info = reader.next_frame(&mut pixelbuf)?;
let stream = TcpStream::connect("151.217.15.79:1337")?;
let mut reader = BufReader::new(stream.try_clone()?);
let mut writer = BufWriter::with_capacity(65536, stream);
write!(writer, "SIZE\n")?;
writer.flush()?;
let mut buf = String::new();
reader.read_line(&mut buf)?;
let size = sscanf!(&buf[..buf.len() - 1], "SIZE {u32} {u32}")?;
thread::scope(|s| {
for _ in 0..32 {
s.spawn(|| -> Result<(), Box<dyn Error + Send + Sync>> {
let stream = TcpStream::connect("151.217.15.79:1337")?;
// disable Nagle's algorithm
stream.set_nodelay(true)?;
let mut reader = BufReader::new(stream.try_clone()?);
let mut writer = BufWriter::with_capacity(4 * 1024 * 1024, stream);
write!(writer, "SIZE\n")?;
writer.flush()?;
let mut buf = String::new();
reader.read_line(&mut buf)?;
// XXX sscanf does not like \n after numbers ... O_o
// XXX sscanf returns Result<(), Box<dyn Error>> which is not + Send + Sync
let size = sscanf!(&buf[..buf.len() - 1], "SIZE {u32} {u32}").unwrap();
let mut rng = thread_rng();
loop {
let pos = (
rng.gen_range(0..size.0 - info.width),
rng.gen_range(0..size.1 - info.height),
);
for x in 0..info.width {
for y in 0..info.height {
match info.color_type {
ColorType::GrayscaleAlpha => {
let offset = ((x + y * info.width) * 2) as usize;
if pixelbuf[offset + 1] != 0 {
write!(
writer,
"PX {} {} {:02x}{:02x}{:02x}\n",
x + pos.0,
y + pos.1,
pixelbuf[offset],
pixelbuf[offset],
pixelbuf[offset]
)?;
let mut rng = thread_rng();
loop {
let pos = (
rng.gen_range(0..size.0 - info.width),
rng.gen_range(0..size.1 - info.height),
);
for x in 0..info.width {
for y in 0..info.height {
match info.color_type {
ColorType::GrayscaleAlpha => {
let offset = ((x + y * info.width) * 2) as usize;
if pixelbuf[offset + 1] != 0 {
write!(
writer,
"PX {} {} {:02x}{:02x}{:02x}\n",
x + pos.0,
y + pos.1,
pixelbuf[offset],
pixelbuf[offset],
pixelbuf[offset]
)?;
}
}
_ => todo!("Unsupported color type"),
}
}
}
_ => todo!("Unsupported color type"),
}
}
});
}
}
});
Ok(())
}