Expand description
mpsc_requests rewritten for crossbeam, written by @stjepang (https://github.com/crossbeam-rs/crossbeam/issues/353#issuecomment-484013974)
crossbeam_requests is a small library built on top of crossbeam-channel but with the addition of the consumer responding with a message to the producer. Since the producer no longer only produces and the consumer no longer only consumes, the Producer is renamed to RequestSender and the Consumer is renamed to RequestReceiver.
This library is based on crossbeam-requests instead of mpsc channels in the standard library because crossbeam has better performance and better compatibility with android.
A perfect use-case for this library is single-threaded databases which need to be accessed from multiple threads (such as SQLite)
Here’s a diagram of the dataflow
|–––––––––––––––––––––––––––––––––––––––––––| | Thread | Request thread | Respond thread | Request thread | |–––––––––––––––––––––––––––––––––––––––––––| | Struct | RequestSender -> RequestReceiver -> ResponseSender -> ResponseReceiver | | (methods) | (request) -> (poll, poll_loop) -> (respond) -> (collect) | |–––––––––––––––––––––––––––––––––––––––––––|
§Examples
For more examples, see the examples directory
For even more examples see the tests in the tests directory
§Simple echo example
use std::thread;
use crossbeam_requests::channel;
type RequestType = String;
type ResponseType = String;
let (requester, responder) = channel::<RequestType, ResponseType>();
thread::spawn(move || {
responder.poll_loop(|req, res_sender| {
res_sender.respond(req);
});
});
let msg = String::from("Hello");
let receiver = requester.request(msg.clone()).unwrap();
let res = receiver.collect().unwrap();
assert_eq!(res, msg);
Structs§
- Request
Receiver - A RequestReceiver listens to requests. Requests are a tuple of a message and a ResponseSender which is used to respond back to the ResponseReceiver
- Request
Sender - RequestSender has a connection to a RequestReceiver to which it can send a requests to. The request method is used to make a request and it returns a ResponseReceiver which is used to receive the response.
- Response
Receiver - ResponseReceiver listens for a response from a ResponseSender. The response is received using the collect method.
- Response
Sender - A ResponseSender is received from the RequestReceiver to respond to the request back to the RequestSender
Enums§
- Request
Error - Errors which can occur when a RequestReceiver handles a request
Functions§
- channel
- Create a RequestSender and a RequestReceiver with a channel between them