multithreaded/
multithreaded.rs

1//! randomx4r example that calculates many hashes using multiple
2//! threads.
3
4use randomx_bindings::*;
5use std::sync::Arc;
6use std::thread;
7use std::time::Instant;
8use std::vec::Vec;
9
10fn main() {
11    const NUM_THREADS: u32 = 8;
12    // number of hashes to perform in each thread, not the total.
13    const NUM_HASHES: u32 = 5000;
14
15    let start = Instant::now();
16
17    // Try adding `| RandomxFlags::LARGEPAGES`.
18    let flags = RandomxFlags::default() | RandomxFlags::FULLMEM;
19    let dataset = Arc::new(RandomxDataset::new(flags, b"key", NUM_THREADS as u8).unwrap());
20
21    println!("Dataset initialised in {}ms", start.elapsed().as_millis());
22
23    let mut handles = Vec::new();
24
25    let start = Instant::now();
26
27    for i in 0..NUM_THREADS {
28        let dataset = dataset.clone();
29
30        handles.push(thread::spawn(move || {
31            let mut nonce: u32 = i;
32            let vm = RandomxVm::new_fast(flags, &dataset).unwrap();
33
34            for _ in 0..NUM_HASHES {
35                let _ = vm.hash(&nonce.to_be_bytes());
36
37                // e.g. thread 0 will use nonces 0, 8, 16, ...
38                // and thread 1 will use nonces 1, 9, 17, ...
39                nonce += NUM_THREADS;
40            }
41        }));
42    }
43
44    for handle in handles {
45        let _ = handle.join();
46    }
47
48    println!(
49        "Completed {} hashes in {}ms",
50        NUM_THREADS * NUM_HASHES,
51        start.elapsed().as_millis()
52    );
53}