使用旧的 Rust 2015
0.1.0 |
|
---|
#22 在 #multi-thread
5KB
64 行
tokio-pool
TokioPool 是一个库,旨在帮助您通过提供可以分配负载的线程池来多线程化您的 Tokio 应用程序。
lib.rs
:
TokioPool 是一个库,旨在帮助您通过提供可以分配负载的线程池来多线程化您的 Tokio 应用程序。
示例
#
#
#
// Create a pool with 4 workers
let (pool, join) = TokioPool::new(4)
.expect("Failed to create event loop");
// Wrap it in an Arc to share it with the listener worker
let pool = Arc::new(pool);
// We can listen on 8080
let addr: SocketAddr = "0.0.0.0:8080".parse().unwrap();
// Clone the pool reference for the listener worker
let pool_ref = pool.clone();
// Use the first pool worker to listen for connections
pool.next_worker().spawn(move |handle| {
// Bind a TCP listener to our address
let listener = TcpListener::bind(&addr, handle).unwrap();
// Listen for incoming clients
listener.incoming().for_each(move |(socket, addr)| {
pool_ref.next_worker().spawn(move |handle| {
// Do work with a client socket
});
Ok(())
}).map_err(|_| ()) // You might want to log these errors or something
});
// You might call `join.join()` here, I don't in this example so that
// `cargo test` doesn't wait forever.
依赖项
~6MB
~94K SLoC