CpuPool

Here, we'll reuse an existing microservice and remove the start_worker function, and the WorkerRequest and WorkerResult types. Keep the convert function and add a new dependency to Cargo.toml:

futures-cpupool = "0.1"

Import the CpuPool type from that crate:

use futures_cpupool::CpuPool;

The pool is now ready to use in the request handler. We can pass it as a parameter, like we did with the Sender of the worker thread in the previous example:

fn main() {
let addr = ([127, 0, 0, 1], 8080).into();
let pool = CpuPool::new(4);
let builder = Server::bind(&addr);
let server = builder.serve(move || {
let pool = pool.clone();
service_fn(move |req| microservice_handler(pool.clone(), req))
});
let server = server.map_err(drop);
hyper::rt::run(server);
}

In the preceding code, we created a thread pool with four threads and passed it to the serve function to clone it for the handler. The handler function takes a pool as the first argument:

fn microservice_handler(pool: CpuPool, req: Request<Body>)
-> Box<Future<Item=Response<Body>, Error=Error> + Send>

We use the same branches and the code to extract the width and height parameters. We change how we convert the image, however:

let body = req.into_body()
.map_err(other)
.concat2()
.map(|chunk| chunk.to_vec())
.and_then(move |buffer| {
let task = future::lazy(move || convert(&buffer, width, height));
pool.spawn(task).map_err(other)
})
.map(|resp| Response::new(resp.into()));

The code of this implementation has become more compact and accurate. In this implementation, we also collect a body to a Vec binary, but to convert the image we use a lazy Future that spawned in a thread pool using the spawn method of CpuPool.

We use the future::lazy call to postpone the execution of the convert function. Without the lazy call, the convert function will be called immediately and will block all IO activities. You can also set specific parameters for CpuPool using Bulder. This helps to set the quantity of threads in a pool, the stack size, and the hooks that will be called after the start of a new thread and before it stops.

CpuPool is not the only way to use pools. Let's look at another example.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.45.80