有没有比RwLock更低级的替代方案?

huangapple go评论70阅读模式
英文:

Is there a lower-level alternative to RwLock?

问题

在我的较低级别库中,我想要一个RwLock的功能,但是不想持有RwLockReadGuardRwLockWriteGuard,而是想要手动告诉RwLock-类似的对象何时释放读取或写入锁定。

在std中是否有可移植的公共接口来实现这个,即使是不安全的?

英文:

In my low-ish level library, I want the functionality of a RwLock, but instead of holding a RwLockReadGuard or RwLockWriteGuard, I want to manually tell the RwLock-like object when the read or write lock has been released.

Is there portable public interface in std for this, even if unsafe?

答案1

得分: 2

不在标准库中(尽管您可以使用 RwLock<()>,但仍需持有守卫),但在 parking_lot 中有 RawRwLock

use parking_lot::lock_api::RawRwLock as _;
use parking_lot::RawRwLock;

let rwlock = RawRwLock::INIT;

// 写访问
rwlock.lock_exclusive();
// 进行操作
unsafe {
    rwlock.unlock_exclusive();
}

// 读访问
rwlock.lock_shared();
// 进行操作
unsafe {
    rwlock.unlock_shared();
}
英文:

Not in std (although you can use RwLock<()>, but you still have to hold the guard around), but in parking_lot there is RawRwLock:

use parking_lot::lock_api::RawRwLock as _;
use parking_lot::RawRwLock;

let rwlock = RawRwLock::INIT;

// Write access
rwlock.lock_exclusive();
// Do work
unsafe {
    rwlock.unlock_exclusive();
}

// Read access
rwlock.lock_shared();
// Do work
unsafe {
    rwlock.unlock_shared();
}

答案2

得分: 1

你可以始终这样做:

let lock = RwLock::new(0);
let mut guard = lock.write().unwrap();
*guard += 1;
drop(guard);
// lock is unlocked now.

let guard = lock.read().unwrap();
println!("{}", *guard);
drop(guard);
// lock is unlocked now.
英文:

You always can do this:

let lock = RwLock::new(0);
let mut guard = lock.write().unwrap();
*guard += 1;
drop(guard);
// lock is unlocked now.

let guard = lock.read().unwrap();
println!("{}", *guard);
drop(guard);
// lock is unlocked now.

huangapple
  • 本文由 发表于 2023年5月21日 19:49:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76299769.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定