Another update from ingydotnet^djgoku

This commit is contained in:
Ingy döt Net 2015-11-18 06:14:39 +00:00
parent 91df62d461
commit 948b86eafa
7604 changed files with 108452 additions and 22726 deletions

View file

@ -0,0 +1,61 @@
#include <future>
#include <iostream>
#include <fstream>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
struct lock_queue
{
std::queue<std::string> q;
std::mutex mutex;
};
void reader(std::string filename, std::future<size_t> lines, lock_queue& out)
{
std::string line;
std::ifstream in(filename);
while(std::getline(in, line)) {
line += '\n';
std::lock_guard<std::mutex> lock(out.mutex);
out.q.push(line);
} {
std::lock_guard<std::mutex> lock(out.mutex);
out.q.push("");
}
lines.wait();
std::cout << "\nPrinted " << lines.get() << " lines\n";
}
void printer(std::promise<size_t> lines, lock_queue& in)
{
std::string s;
size_t line_n = 0;
bool print = false;
while(true) {
{
std::lock_guard<std::mutex> lock(in.mutex);
if(( print = not in.q.empty() )) { //Assignment intended
s = in.q.front();
in.q.pop();
}
}
if(print) {
if(s == "") break;
std::cout << s;
++line_n;
print = false;
}
}
lines.set_value(line_n);
}
int main()
{
lock_queue queue;
std::promise<size_t> promise;
std::thread t1(reader, "input.txt", promise.get_future(), std::ref(queue));
std::thread t2(printer, std::move(promise), std::ref(queue));
t1.join(); t2.join();
}

View file

@ -0,0 +1,44 @@
use std::fs::File;
use std::io::BufReader;
use std::io::BufRead;
use std::thread::spawn;
use std::sync::mpsc::{SyncSender, Receiver, sync_channel};
fn main() {
let (tx, rx): (SyncSender<String>, Receiver<String>) = sync_channel::<String>(0);
// Reader thread.
spawn(move || {
let file = File::open("input.txt").unwrap();
let reader = BufReader::new(file);
for line in reader.lines() {
match line {
Ok(msg) => tx.send(msg).unwrap(),
Err(e) => println!("{}", e)
}
}
drop(tx);
});
// Writer thread.
spawn(move || {
let mut loop_count: u16 = 0;
loop {
let recvd = rx.recv();
match recvd {
Ok(msg) => {
println!("{}", msg);
loop_count += 1;
},
Err(_) => break // rx.recv() will only err when tx is closed.
}
}
println!("Line count: {}", loop_count);
}).join().unwrap();
}