Skip to content

Add CritToken struct #13

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

Closed
wants to merge 1 commit into from
Closed
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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased]

### Added

- `interrupt::CritToken`, a struct that only exists in a critical section.

### Changed

- The closure that `interrupt::free` takes now takes a reference to an `interrupt::CritToken`.

## [v0.1.5]

### Added
Expand Down
15 changes: 12 additions & 3 deletions src/interrupt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,22 @@ impl<T> Mutex<T> {
pub fn lock<F, R>(&self, f: F) -> R
where F: FnOnce(&mut T) -> R
{
unsafe { ::interrupt::free(|| f(&mut *self.inner.get())) }
unsafe { ::interrupt::free(|_| f(&mut *self.inner.get())) }
}
}

// FIXME `T` should have some bound: `Send` or `Sync`?
unsafe impl<T> Sync for Mutex<T> {}

/// A struct whos existence guarantees that interrupts are disabled
///
/// This struct is zero-sized and cannot be initialized by user code. An
/// instance is only ever created in the `free` function, which passes the
/// instance to the closure. This allows a user to force a function to only
/// ever be called in a critical section by taking a reference to a `CritToken`
/// as a parameter.
pub struct CritToken(());

/// Disable interrupts, globally
#[inline(always)]
pub unsafe fn disable() {
Expand Down Expand Up @@ -58,13 +67,13 @@ pub unsafe fn enable() {
/// Execute closure `f` in an interrupt-free context.
/// This as also known as a "critical section".
pub unsafe fn free<F, R>(f: F) -> R
where F: FnOnce() -> R
where F: FnOnce(&CritToken) -> R
{
let primask = ::register::primask::read();

disable();

let r = f();
let r = f(&CritToken(()));

// If the interrupts were enabled before our `disable` call, then re-enable
// them. Otherwise, keep them disabled
Expand Down