Skip to main content

Semaphore

Struct Semaphore 

Source
pub struct Semaphore { /* private fields */ }
Expand description

A Semaphore maintains the number of permits it is still allowed to give.

  • When acquire() is called and the semaphore still has permits to give, it will return a Permit. If there are no permits that can be given, it will wait for one permit to be given back from a thread so that it can return a new Permit.
  • When try_acquire() is called and the semaphore still has permits to give, it will return Some(Permit). If there are no permits that can be given, it will return None.

Implementations§

Source§

impl Semaphore

Source

pub fn new(permits: usize) -> Arc<Self>

Returns a new Arc<Semaphore> with the limit of permits chosen by you.

Examples found in repository?
examples/main.rs (line 7)
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 available_machine_parallelism = available_parallelism().unwrap().get();
20
21    let semaphore = simple_semaphore::Semaphore::new_available_parallelism().unwrap(); // Also uses `available_parallelism()` internally
22    for _ in 0..(available_machine_parallelism + 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(
34        (((available_machine_parallelism + 1) * 1000) / 2) as u64,
35    ));
36}
Source

pub fn new_available_parallelism() -> Result<Arc<Self>, String>

Returns a new Arc<Semaphore> with the limit of permits set to the machine’s parallelism value, usually CPU cores.

Examples found in repository?
examples/main.rs (line 21)
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 available_machine_parallelism = available_parallelism().unwrap().get();
20
21    let semaphore = simple_semaphore::Semaphore::new_available_parallelism().unwrap(); // Also uses `available_parallelism()` internally
22    for _ in 0..(available_machine_parallelism + 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(
34        (((available_machine_parallelism + 1) * 1000) / 2) as u64,
35    ));
36}
Source

pub fn available_permits(self: &Arc<Self>) -> usize

Returns the number of available permits

Source

pub fn acquire(self: &Arc<Self>) -> Permit

Tries to get a Permit. If no more permits can be given, it will wait for one permit to be given back from a thread so that it can return a new Permit.

Examples found in repository?
examples/main.rs (line 12)
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 available_machine_parallelism = available_parallelism().unwrap().get();
20
21    let semaphore = simple_semaphore::Semaphore::new_available_parallelism().unwrap(); // Also uses `available_parallelism()` internally
22    for _ in 0..(available_machine_parallelism + 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(
34        (((available_machine_parallelism + 1) * 1000) / 2) as u64,
35    ));
36}
Source

pub fn try_acquire(self: &Arc<Self>) -> Option<Permit>

Tries to get a Option<Permit>. If no more permits can be given, it will return None.

Examples found in repository?
examples/main.rs (line 25)
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 available_machine_parallelism = available_parallelism().unwrap().get();
20
21    let semaphore = simple_semaphore::Semaphore::new_available_parallelism().unwrap(); // Also uses `available_parallelism()` internally
22    for _ in 0..(available_machine_parallelism + 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(
34        (((available_machine_parallelism + 1) * 1000) / 2) as u64,
35    ));
36}
Source

pub fn release(&self)

Releases a permit. This is what drop() on Permit calls, ideally use drop(permit).

Trait Implementations§

Source§

impl Debug for Semaphore

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.