#cpu #process #thread #multi-thread

multithreading

A simple multithreading library in Rust

5 releases

0.1.4 Mar 26, 2024
0.1.3 Mar 26, 2024
0.1.2 Mar 25, 2024
0.1.1 Mar 8, 2024
0.1.0 Mar 8, 2024

#254 in Concurrency

Download history 190/week @ 2024-03-05 80/week @ 2024-03-12 74/week @ 2024-03-19 240/week @ 2024-03-26 48/week @ 2024-04-02 6/week @ 2024-04-09

368 downloads per month

MIT license

8KB
163 lines

Multithreading Library Written In Rust


A simple multithreading library written in rust.

Usage

use multithreading::ThreadPool;

fn main() {
    let pool = ThreadPool::new(/*<number_of_threads_to_use>*/);
    for i in 0..10 {
        pool.execute(move || {
            // Do something
            println!("Task {}", i);
        });
    }
}

if you want to use all available cores in your cpu set number_of_threads_to_use to 0.

use multithreading::ThreadPool;
use num_cpus;

fn main() {
    let pool = ThreadPool::new(0);
    for i in 0..10 {
        pool.execute(move || {
            // Do something
            println!("Task {}", i);
        });
    }
}

You can also get the result of executing something since it returns a receiver.

Example

use multithreading::ThreadPool;

fn main() {
    let pool = ThreadPool::new(4);
    let a: u8 = 1;
    let b: u8 = 3;
    let receiver = pool.execute(move || {
        a + b
    });

    let result = receiver.recv().unwrap(); // The value of this is 4 (3+1). 
    assert_eq!(result, 4);
}

Dependencies

~76KB