-
I am writing a program (specifically, a BitTorrent client) and it has many logical jobs (download jobs). For any job, many net connections are associated with the job, and new connections may join or leave the job. Every connection of a job basically do the same operations, for example, for every connection, there are 2 operations:
I can think of 2 approaches to implement this. Approach 1: Spawn a tokio task for every connection, and use some sync mechanisms to sync states with the job controller. async fn connection_task(c: TcpConn, controller: Arc<JobController>) {
let rx = controller.command_handle_of(c);
select! {
msg = receive_income_msg_from(c) => {
some_sync_operation(msg, controller);
}
msg = outcome_msg_from_controller(rx) => {
send_msg_through(c, msg);
}
}
} Approach 2: Use an event loop, like async fn job_controller(cmd_rx: Receiver<Cmd>) {
let conns = some_epoll_like_struct::new();
loop {
select! {
c = conns.is_ready() => {
if write_ready(c) {
send_data_through(c, pending_send(c).pop_one());
if no_more_pending_send(c) {
conns.set_interest(c, Interest::Read);
}
}
if read_ready(c) {
read_data_from(c);
}
do_some_controller_work();
// maybe plan to send data through other connection
if let (other_conn, msg) = maybe_need_send_new_data() {
pending_send(other_conn).append(msg);
conns.set_interest(other_conn, Interest::Read | Interest::Write);
}
}
cmd{connection: c, cmd: cmd} = cmd_rx.recv() => {
match cmd {
AddConn => conn.add(c);
RemoveConn => conn.remove(c);
}
}
}
}
} My question is: Is approach 2 suggested or not in tokio? And if viable, how to implement that? One implementation I come up with is combining many A more "rust async style" way is having a To my knowledge, it is not that simple as the pseudocode, I have some experience in C and sync Rust, but not much in tokio or async Rust. Any discussion will be helpful. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Spawn a task per connection. You may find this article and talk useful for how to design programs with one task per connection. |
Beta Was this translation helpful? Give feedback.
Spawn a task per connection. You may find this article and talk useful for how to design programs with one task per connection.