英文:
Is there a lower-level alternative to RwLock?
问题
在我的较低级别库中,我想要一个RwLock
的功能,但是不想持有RwLockReadGuard
或RwLockWriteGuard
,而是想要手动告诉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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论