@@ -8,7 +8,7 @@ use tokio::net::TcpListener;
88use std:: future:: Future ;
99use std:: net:: SocketAddr ;
1010use std:: pin:: Pin ;
11- use std:: sync:: Mutex ;
11+ use std:: sync:: { Arc , Mutex } ;
1212
1313#[ path = "../benches/support/mod.rs" ]
1414mod support;
@@ -23,28 +23,25 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
2323 let listener = TcpListener :: bind ( addr) . await ?;
2424 println ! ( "Listening on http://{}" , addr) ;
2525
26+ let svc = Svc {
27+ counter : Arc :: new ( Mutex :: new ( 0 ) ) ,
28+ } ;
29+
2630 loop {
2731 let ( stream, _) = listener. accept ( ) . await ?;
2832 let io = TokioIo :: new ( stream) ;
29-
33+ let svc_clone = svc . clone ( ) ;
3034 tokio:: task:: spawn ( async move {
31- if let Err ( err) = http1:: Builder :: new ( )
32- . serve_connection (
33- io,
34- Svc {
35- counter : Mutex :: new ( 81818 ) ,
36- } ,
37- )
38- . await
39- {
35+ if let Err ( err) = http1:: Builder :: new ( ) . serve_connection ( io, svc_clone) . await {
4036 println ! ( "Failed to serve connection: {:?}" , err) ;
4137 }
4238 } ) ;
4339 }
4440}
4541
42+ #[ derive( Debug , Clone ) ]
4643struct Svc {
47- counter : Mutex < Counter > ,
44+ counter : Arc < Mutex < Counter > > ,
4845}
4946
5047impl Service < Request < IncomingBody > > for Svc {
@@ -57,6 +54,10 @@ impl Service<Request<IncomingBody>> for Svc {
5754 Ok ( Response :: builder ( ) . body ( Full :: new ( Bytes :: from ( s) ) ) . unwrap ( ) )
5855 }
5956
57+ if req. uri ( ) . path ( ) != "/favicon.ico" {
58+ * self . counter . lock ( ) . expect ( "lock poisoned" ) += 1 ;
59+ }
60+
6061 let res = match req. uri ( ) . path ( ) {
6162 "/" => mk_response ( format ! ( "home! counter = {:?}" , self . counter) ) ,
6263 "/posts" => mk_response ( format ! ( "posts, of course! counter = {:?}" , self . counter) ) ,
@@ -68,10 +69,6 @@ impl Service<Request<IncomingBody>> for Svc {
6869 _ => return Box :: pin ( async { mk_response ( "oh no! not found" . into ( ) ) } ) ,
6970 } ;
7071
71- if req. uri ( ) . path ( ) != "/favicon.ico" {
72- * self . counter . lock ( ) . expect ( "lock poisoned" ) += 1 ;
73- }
74-
7572 Box :: pin ( async { res } )
7673 }
7774}
0 commit comments