@@ -8,7 +8,7 @@ use tokio::net::TcpListener;
8
8
use std:: future:: Future ;
9
9
use std:: net:: SocketAddr ;
10
10
use std:: pin:: Pin ;
11
- use std:: sync:: Mutex ;
11
+ use std:: sync:: { Arc , Mutex } ;
12
12
13
13
#[ path = "../benches/support/mod.rs" ]
14
14
mod support;
@@ -23,28 +23,25 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
23
23
let listener = TcpListener :: bind ( addr) . await ?;
24
24
println ! ( "Listening on http://{}" , addr) ;
25
25
26
+ let svc = Svc {
27
+ counter : Arc :: new ( Mutex :: new ( 0 ) ) ,
28
+ } ;
29
+
26
30
loop {
27
31
let ( stream, _) = listener. accept ( ) . await ?;
28
32
let io = TokioIo :: new ( stream) ;
29
-
33
+ let svc_clone = svc . clone ( ) ;
30
34
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 {
40
36
println ! ( "Failed to serve connection: {:?}" , err) ;
41
37
}
42
38
} ) ;
43
39
}
44
40
}
45
41
42
+ #[ derive( Debug , Clone ) ]
46
43
struct Svc {
47
- counter : Mutex < Counter > ,
44
+ counter : Arc < Mutex < Counter > > ,
48
45
}
49
46
50
47
impl Service < Request < IncomingBody > > for Svc {
@@ -57,6 +54,10 @@ impl Service<Request<IncomingBody>> for Svc {
57
54
Ok ( Response :: builder ( ) . body ( Full :: new ( Bytes :: from ( s) ) ) . unwrap ( ) )
58
55
}
59
56
57
+ if req. uri ( ) . path ( ) != "/favicon.ico" {
58
+ * self . counter . lock ( ) . expect ( "lock poisoned" ) += 1 ;
59
+ }
60
+
60
61
let res = match req. uri ( ) . path ( ) {
61
62
"/" => mk_response ( format ! ( "home! counter = {:?}" , self . counter) ) ,
62
63
"/posts" => mk_response ( format ! ( "posts, of course! counter = {:?}" , self . counter) ) ,
@@ -68,10 +69,6 @@ impl Service<Request<IncomingBody>> for Svc {
68
69
_ => return Box :: pin ( async { mk_response ( "oh no! not found" . into ( ) ) } ) ,
69
70
} ;
70
71
71
- if req. uri ( ) . path ( ) != "/favicon.ico" {
72
- * self . counter . lock ( ) . expect ( "lock poisoned" ) += 1 ;
73
- }
74
-
75
72
Box :: pin ( async { res } )
76
73
}
77
74
}
0 commit comments