#arc #sync #write #mutex #synchronized

synchronized-writer

A tiny implement for synchronously writing data

2 stable releases

1.1.0 Oct 24, 2018
1.0.0 Oct 24, 2018

#11 in #arc

Download history 15/week @ 2018-10-26

5 downloads per month

MIT license

8KB
91 lines

Synchronized Writer

Build Status Build status

A tiny implement for synchronously writing data.

Examples

SynchronizedWriter

extern crate synchronized_writer;

use synchronized_writer::SynchronizedWriter;
use std::sync::{Arc, Mutex, mpsc};
use std::thread;
use std::io::Write;

let data = Mutex::new(Vec::new());

let data_arc = Arc::new(data);

let (tx, rx) = mpsc::channel();

for _ in 0..10 {
    let mut writer = SynchronizedWriter::new(data_arc.clone());

    let tx = tx.clone();

    thread::spawn(move || {
        writer.write(b"Hello world!").unwrap();
        tx.send(0).unwrap();
    });
}

for _ in 0..10 {
    rx.recv().unwrap();
}

assert_eq!(b"Hello world!Hello world!Hello world!Hello world!Hello world!Hello world!Hello world!Hello world!Hello world!Hello world!".to_vec(), *data_arc.lock().unwrap());

SynchronizedOptionWriter

extern crate synchronized_writer;

use synchronized_writer::SynchronizedOptionWriter;
use std::sync::{Arc, Mutex};
use std::io::Write;

let data = Mutex::new(Some(Vec::new()));

let data_arc = Arc::new(data);

let mut writer = SynchronizedOptionWriter::new(data_arc.clone());

writer.write(b"Hello world!").unwrap();

writer.flush().unwrap();

let data = data_arc.lock().unwrap().take().unwrap(); // remove out the vec from arc

assert_eq!(b"Hello world!".to_vec(), data);

Crates.io

https://crates.io/crates/synchronized-writer

Documentation

https://docs.rs/synchronized-writer

License

MIT

No runtime deps