Rust 如何为超级处理程序共享可变状态?
作为一个非常简单的例子,我正在尝试编写一个简单回复的Web服务器 此页面已被请求$N次 但是我在共享可变状态时遇到了很多困难。以下是我最好的尝试:Rust 如何为超级处理程序共享可变状态?,rust,Rust,作为一个非常简单的例子,我正在尝试编写一个简单回复的Web服务器 此页面已被请求$N次 但是我在共享可变状态时遇到了很多困难。以下是我最好的尝试: extern crate hyper; use hyper::Server; use hyper::server::Request; use hyper::server::Response; struct World { count: i64, } impl World { fn greet(&mut self, req
extern crate hyper;
use hyper::Server;
use hyper::server::Request;
use hyper::server::Response;
struct World {
count: i64,
}
impl World {
fn greet(&mut self, req: Request, res: Response) {
self.count += 1;
let str: String = format!("this page has been requested {} times", self.count);
res.send(str.as_bytes()).unwrap();
}
}
fn main() {
println!("Started..");
let mut w = World { count: 0 };
Server::http("127.0.0.1:3001").unwrap()
.handle(move |req: Request, res: Response| w.greet(req, res) ).unwrap();
}
由于请求处理可能发生在不同的线程中,因此您需要同步对全局状态的访问,为此您需要使用以下内容:
您可以从的签名中找到这一点:它要求其处理程序是
handler+'static
,而它本身要求Send+Sync
。因此,此闭包捕获的所有内容也必须是静态+发送+同步的,也就是说,可以从多个线程安全访问。包装到互斥锁中的值通常满足这些要求(当然,如果它们不包含引用)。顺便说一下:如果它是一个简单的计数器,也可以使用原子*
类型之一,将签名更改为问候(&self,Request,Response)
,并通过fetch\u add
增加计数器。我认为这个答案已经过时了。你有没有可能更新一下?
let w = Mutex::new(World { count: 0 });
Server::http("127.0.0.1:3001").unwrap()
.handle(move |req: Request, res: Response| w.lock().unwrap().greet(req, res))
.unwrap();