Friday 15 August 2014

multithreading - std::sync::Arc of trait in Rust -



multithreading - std::sync::Arc of trait in Rust -

i trying implement library making tcp servers.

this simplified code problem:

#![crate_name="http_server2"] #![crate_type="lib"] utilize std::io::{tcplistener, listener, acceptor, tcpstream, ioresult, reader, writer}; utilize std::ops::fn; utilize std::sync::arc; pub trait handler: sized + send { fn do_it(s: tcpstream) -> ioresult<()>; } fn serve(handler: arc<handler + sized>) -> ioresult<()> { allow listener = tcplistener::bind("127.0.0.1", 1234); stream in try!(listener.listen()).incoming() { allow stream = try!(stream); allow handler = handler.clone(); spawn(proc() { handler.do_it(stream); }); } ok(()) }

compiler totally ignores specifications of handler + sized. if implement construction trait handler , seek phone call serve structure, such advice size ignored ( http://is.gd/ows22i ).

<anon>:13:1: 25:2 error: trait `core::kinds::sized` not implemented type `handler+'static+sized` <anon>:13 fn serve(handler: arc<handler + sized>) -> ioresult<()> <anon>:14 { <anon>:15 allow listener = tcplistener::bind("127.0.0.1", 1234); <anon>:16 <anon>:17 stream in try!(listener.listen()).incoming() { <anon>:18 allow stream = try!(stream); ... <anon>:13:1: 25:2 note: trait `core::kinds::sized` must implemented because required `alloc::arc::arc` <anon>:13 fn serve(handler: arc<handler + sized>) -> ioresult<()> <anon>:14 { <anon>:15 allow listener = tcplistener::bind("127.0.0.1", 1234); <anon>:16 <anon>:17 stream in try!(listener.listen()).incoming() { <anon>:18 allow stream = try!(stream); ... error: aborting due previous error

how can implement 1 template function multithreading take different handlers?

as said in comment above,

use std::io::{tcplistener, listener, acceptor, tcpstream, ioresult, writer}; utilize std::sync::arc; pub trait handler: sized + send { fn do_it(&self, s: tcpstream) -> ioresult<()>; } fn serve<t: handler + sized + send + sync>(handler: arc<t>) -> ioresult<()> { allow listener = tcplistener::bind("127.0.0.1", 1234); stream in try!(listener.listen()).incoming() { allow stream = try!(stream); allow handler = handler.clone(); spawn(proc() { allow _ = handler.do_it(stream); }); } ok(()) } struct hello { x: u32, } impl handler hello { fn do_it(&self, mut s: tcpstream) -> ioresult<()> { s.write_le_u32(self.x) } } fn main() { allow s = arc::new(hello{x: 123,}); allow _ = serve(s); }

compiles fine. (playpen)

changes make do_it take &self. make serve generic, adding type parameter constraints want. make impl of handler hello in do_it not discard result of write (remove ;). clarify let _ = ... intentionally discard result.

you not able execute in playpen though (application terminated abnormally signal 31 (bad scheme call)), playpen forbids io (network io in case). runs fine on local box though.

multithreading rust traits rust-crates

No comments:

Post a Comment