main/
main.rs

1use std::thread;
2use std::{sync::Arc, time::Duration};
3
4extern crate simple_semaphore;
5
6fn main() {
7    let semaphore = simple_semaphore::Semaphore::new(2);
8
9    for _ in 0..5 {
10        let semaphore = Arc::clone(&semaphore);
11        thread::spawn(move || {
12            let permit = semaphore.acquire();
13            thread::sleep(Duration::from_millis(500));
14            drop(permit);
15        });
16    }
17    thread::sleep(Duration::from_millis(3000));
18
19    let cores = num_cpus::get();
20
21    let semaphore = simple_semaphore::Semaphore::default(); // Also uses `num_cpus::get()` internally
22    for _ in 0..(cores + 2) {
23        let semaphore = Arc::clone(&semaphore);
24        thread::spawn(move || {
25            if let Some(permit) = semaphore.try_acquire() {
26                thread::sleep(Duration::from_millis(500));
27                drop(permit);
28            } else {
29                println!("Too many permits given, exiting the thread"); // Will be printed twice
30            }
31        });
32    }
33    thread::sleep(Duration::from_millis((((cores + 1) * 1000) / 2) as u64));
34}