gpt4 book ai didi

rust - 有没有办法在 RwLock drop 上运行闭包?

转载 作者:行者123 更新时间:2023-11-29 08:25:54 26 4
gpt4 key购买 nike

我有一个程序将可变状态隐藏在 RwLock 后面。我想做的是,当它被可变借用时(RW_LOCK.write()),在删除时它应该做一些事情(即尝试写入文件,清理 rwlock 后面的数据等)

例如:

let DATA: RwLock<Data> = RwLock::new(Data { content: Default::default() } );

fn do_something() {
let mut state = DATA.write().unwrap();

state.change(5);
// ...
// Here, just before `state` goes out of scope (where it gets dropped and `RwLock` will allow
// other threads read/write access to `Data`, I would like for `RwLock` to auto-run `state.cleanup()`.
}

有没有办法做到这一点,还是我必须重新实现 RwLock

最佳答案

您可以使用包装器类型来做到这一点:

Playground

use std::ops::{Deref, DerefMut, Drop};
use std::sync::{RwLock, RwLockWriteGuard};

type CleanupClosure<'a> = Fn(&mut RwLockWriteGuard<'a, Data>);

struct Data {
content: String,
}

impl Data {
fn change(&mut self, num: i32) {
println!("Changed to {}", num);
self.content = num.to_string();
}
}

struct RwLockWriteWrapper<'a, F: CleanupClosure<'a>>(RwLockWriteGuard<'a, Data>, F);

impl<'a, F: CleanupClosure<'a>> Deref for RwLockWriteWrapper<'a, F> {
type Target = RwLockWriteGuard<'a, Data>;

fn deref(&self) -> &RwLockWriteGuard<'a, Data> {
&self.0
}
}

impl<'a, F: CleanupClosure<'a>> DerefMut for RwLockWriteWrapper<'a, F> {
fn deref_mut(&mut self) -> &mut RwLockWriteGuard<'a, Data> {
&mut self.0
}
}

impl<'a, F: CleanupClosure<'a>> Drop for RwLockWriteWrapper<'a, F> {
fn drop(&mut self) {
println!("Cleaning up!");
self.1(&mut self.0)
}
}

fn main() {
let data: RwLock<Data> = RwLock::new(Data {
content: "Start".to_owned(),
});
do_something(&data);
do_something(&data);
}

fn do_something(data: &RwLock<Data>) {
// Write your own cleanup logic here
let mut state = RwLockWriteWrapper(data.write().unwrap(), |state| {
state.content = "Cleaned up".to_owned()
});

println!("do_something start: {}", state.content);
state.change(5);

println!("do_something after change: {}", state.content);
} // Automatically run cleanup here

它确实要求您在调用 .write() 时记得包装类型。您可以将 RwLock 本身包装在另一种类型中,该类型也会返回 RwLockWriteWrapper 以自动执行此操作。

这确实变得非常冗长,所以我找到了 a crate that impls the deref trait for you .

我仍然不确定您在标题中提到的闭包是什么意思。

关于rust - 有没有办法在 RwLock drop 上运行闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58758812/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com