Skip to content

Commit

Permalink
split guard into read and write types
Browse files Browse the repository at this point in the history
  • Loading branch information
the8472 committed Feb 9, 2021
1 parent 44abad5 commit 4fc181d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 17 deletions.
4 changes: 2 additions & 2 deletions library/std/src/sys/unix/os.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use crate::str;
use crate::sys::cvt;
use crate::sys::fd;
use crate::sys_common::mutex::{StaticMutex, StaticMutexGuard};
use crate::sys_common::rwlock::{RWLockGuard, StaticRWLock};
use crate::sys_common::rwlock::{RWLockReadGuard, StaticRWLock};
use crate::vec;

use libc::{c_char, c_int, c_void};
Expand Down Expand Up @@ -496,7 +496,7 @@ pub unsafe fn environ() -> *mut *const *const c_char {

static ENV_LOCK: StaticRWLock = StaticRWLock::new();

pub fn env_read_lock() -> RWLockGuard {
pub fn env_read_lock() -> RWLockReadGuard {
ENV_LOCK.read_with_guard()
}

Expand Down
29 changes: 14 additions & 15 deletions library/std/src/sys_common/rwlock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,47 +102,46 @@ impl StaticRWLock {
///
/// The lock is automatically unlocked when the returned guard is dropped.
#[inline]
pub fn read_with_guard(&'static self) -> RWLockGuard {
pub fn read_with_guard(&'static self) -> RWLockReadGuard {
// Safety: All methods require static references, therefore self
// cannot be moved between invocations.
unsafe {
self.0.read();
}
RWLockGuard(&self.0, GuardType::Read)
RWLockReadGuard(&self.0)
}

/// Acquires write access to the underlying lock, blocking the current thread
/// to do so.
///
/// The lock is automatically unlocked when the returned guard is dropped.
#[inline]
pub fn write_with_guard(&'static self) -> RWLockGuard {
pub fn write_with_guard(&'static self) -> RWLockWriteGuard {
// Safety: All methods require static references, therefore self
// cannot be moved between invocations.
unsafe {
self.0.write();
}
RWLockGuard(&self.0, GuardType::Write)
RWLockWriteGuard(&self.0)
}
}

#[cfg(unix)]
enum GuardType {
Read,
Write,
pub struct RWLockReadGuard(&'static RWLock);

#[cfg(unix)]
impl Drop for RWLockReadGuard {
fn drop(&mut self) {
unsafe { self.0.read_unlock() }
}
}

#[cfg(unix)]
pub struct RWLockGuard(&'static RWLock, GuardType);
pub struct RWLockWriteGuard(&'static RWLock);

#[cfg(unix)]
impl Drop for RWLockGuard {
impl Drop for RWLockWriteGuard {
fn drop(&mut self) {
unsafe {
match &self.1 {
GuardType::Read => self.0.read_unlock(),
GuardType::Write => self.0.write_unlock(),
}
}
unsafe { self.0.write_unlock() }
}
}

0 comments on commit 4fc181d

Please sign in to comment.