Skip to content

Instantly share code, notes, and snippets.

@jrcavani
Created December 16, 2023 19:31
Show Gist options
  • Save jrcavani/27a4959518692b6685efa0f00bb59bde to your computer and use it in GitHub Desktop.
Save jrcavani/27a4959518692b6685efa0f00bb59bde to your computer and use it in GitHub Desktop.
// use file api
use anyhow::Result;
use std::fs::OpenOptions;
use std::io::{self, Write, Seek, SeekFrom};
use std::thread;
fn write_to_file_at_position(file_path: &str, data: &[u8], position: u64) -> io::Result<()> {
// Open the file in write mode and create it if it doesn't exist
let mut file = OpenOptions::new()
.write(true)
.create(true)
.open(file_path)?;
// Move the file cursor to the specified position
file.seek(SeekFrom::Start(position))?;
// Write the data to the file
file.write_all(data)?;
Ok(())
}
fn main() -> Result<()> {
let file_path = "example.txt";
let data1 = b"Thread 1: Hello, World!";
let data2 = b"Thread 2: Rust is awesome!";
let position1 = 0;
let position2 = 23;
// Spawn two threads, each performing a write operation
let thread1 = thread::spawn(move || {
write_to_file_at_position(file_path, data1, position1)
});
let thread2 = thread::spawn(move || {
write_to_file_at_position(file_path, data2, position2)
});
// Wait for both threads to finish
thread1.join().unwrap()?;
thread2.join().unwrap()?;
Ok(())
}
// use mmap
use anyhow::Result;
use memmap2::MmapOptions;
use std::fs::OpenOptions;
use std::thread;
fn main() -> Result<()> {
// Open or create a file
let file_path = "example.txt";
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(file_path)?;
// Set the file size
file.set_len(49)?;
// Create a memory map for the first region (unsafe)
let mut mmap1 = unsafe {
MmapOptions::new().map_mut(&file)?
};
// Create a memory map for the second region (unsafe)
let mut mmap2 = unsafe {
MmapOptions::new().map_mut(&file)?
};
// Schedule writes to different non-overlapping parts of the mmapped file
let thread1 = thread::spawn(move || {
let data = b"Thread 1: Hello, World!";
let position = 0;
mmap1[position..position + data.len()].copy_from_slice(data);
});
let thread2 = thread::spawn(move || {
let data = b"Thread 2: Rust is awesome!";
let position = 23;
mmap2[position..position + data.len()].copy_from_slice(data);
});
// Wait for both threads to finish
thread1.join().unwrap();
thread2.join().unwrap();
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment