Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setup a faster, less footgun-prone API #105

Merged
merged 6 commits into from
Feb 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ optional = true

[dev-dependencies]
futures-lite = "2.0.0"
try-lock = "0.2.5"
waker-fn = "1"

[dev-dependencies.criterion]
Expand Down
19 changes: 5 additions & 14 deletions benches/bench.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,22 @@
use std::iter;
use std::pin::Pin;

use criterion::{criterion_group, criterion_main, Criterion};
use event_listener::{Event, EventListener};
use event_listener::{Event, Listener};

const COUNT: usize = 8000;

fn bench_events(c: &mut Criterion) {
c.bench_function("notify_and_wait", |b| {
let ev = Event::new();
let mut handles = iter::repeat_with(EventListener::new)
.take(COUNT)
.collect::<Vec<_>>();
let mut handles = Vec::with_capacity(COUNT);

b.iter(|| {
for handle in &mut handles {
// SAFETY: The handle is not moved out.
let listener = unsafe { Pin::new_unchecked(handle) };
listener.listen(&ev);
}
handles.extend(iter::repeat_with(|| ev.listen()).take(COUNT));

ev.notify(COUNT);

for handle in &mut handles {
// SAFETY: The handle is not moved out.
let listener = unsafe { Pin::new_unchecked(handle) };
listener.wait();
for handle in handles.drain(..) {
handle.wait();
}
});
});
Expand Down
99 changes: 36 additions & 63 deletions examples/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,21 @@
mod example {
#![allow(dead_code)]

use std::cell::UnsafeCell;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc};
use std::thread;
use std::time::{Duration, Instant};

use event_listener::Event;
use event_listener::{listener, Event, Listener};
use try_lock::{Locked, TryLock};

/// A simple mutex.
struct Mutex<T> {
/// Set to `true` when the mutex is locked.
locked: AtomicBool,

/// Blocked lock operations.
lock_ops: Event,

/// The inner protected data.
data: UnsafeCell<T>,
/// The inner non-blocking mutex.
data: TryLock<T>,
}

unsafe impl<T: Send> Send for Mutex<T> {}
Expand All @@ -34,119 +30,96 @@ mod example {
/// Creates a mutex.
fn new(t: T) -> Mutex<T> {
Mutex {
locked: AtomicBool::new(false),
lock_ops: Event::new(),
data: UnsafeCell::new(t),
data: TryLock::new(t),
}
}

/// Attempts to acquire a lock.
fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
if !self.locked.swap(true, Ordering::Acquire) {
Some(MutexGuard(self))
} else {
None
}
self.data.try_lock().map(MutexGuard)
}

/// Blocks until a lock is acquired.
fn lock(&self) -> MutexGuard<'_, T> {
let mut listener = None;

loop {
// Attempt grabbing a lock.
if let Some(guard) = self.try_lock() {
return guard;
}

// Set up an event listener or wait for a notification.
match listener.take() {
None => {
// Start listening and then try locking again.
listener = Some(self.lock_ops.listen());
}
Some(mut l) => {
// Wait until a notification is received.
l.as_mut().wait();
}
// Set up an event listener.
listener!(self.lock_ops => listener);

// Try again.
if let Some(guard) = self.try_lock() {
return guard;
}

// Wait for a notification.
listener.wait();
}
}

/// Blocks until a lock is acquired or the timeout is reached.
fn lock_timeout(&self, timeout: Duration) -> Option<MutexGuard<'_, T>> {
let deadline = Instant::now() + timeout;
let mut listener = None;

loop {
// Attempt grabbing a lock.
if let Some(guard) = self.try_lock() {
return Some(guard);
}

// Set up an event listener or wait for an event.
match listener.take() {
None => {
// Start listening and then try locking again.
listener = Some(self.lock_ops.listen());
}
Some(mut l) => {
// Wait until a notification is received.
l.as_mut().wait_deadline(deadline)?;
}
// Set up an event listener.
listener!(self.lock_ops => listener);

// Try again.
if let Some(guard) = self.try_lock() {
return Some(guard);
}

// Wait until a notification is received.
listener.wait_deadline(deadline)?;
}
}

/// Acquires a lock asynchronously.
async fn lock_async(&self) -> MutexGuard<'_, T> {
let mut listener = None;

loop {
// Attempt grabbing a lock.
if let Some(guard) = self.try_lock() {
return guard;
}

// Set up an event listener or wait for an event.
match listener.take() {
None => {
// Start listening and then try locking again.
listener = Some(self.lock_ops.listen());
}
Some(l) => {
// Wait until a notification is received.
l.await;
}
// Set up an event listener.
listener!(self.lock_ops => listener);

// Try again.
if let Some(guard) = self.try_lock() {
return guard;
}

// Wait until a notification is received.
listener.await;
}
}
}

/// A guard holding a lock.
struct MutexGuard<'a, T>(&'a Mutex<T>);

unsafe impl<T: Send> Send for MutexGuard<'_, T> {}
unsafe impl<T: Sync> Sync for MutexGuard<'_, T> {}

impl<T> Drop for MutexGuard<'_, T> {
fn drop(&mut self) {
self.0.locked.store(false, Ordering::Release);
self.0.lock_ops.notify(1);
}
}
struct MutexGuard<'a, T>(Locked<'a, T>);

impl<T> Deref for MutexGuard<'_, T> {
type Target = T;

fn deref(&self) -> &T {
unsafe { &*self.0.data.get() }
&self.0
}
}

impl<T> DerefMut for MutexGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.0.data.get() }
&mut self.0
}
}

Expand Down
Loading
Loading