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.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
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.
Approach 2:
Use an event loop, like
epoll
, which tracks all the interested connections (file descriptors). Once a connection can read or write, do operations on that connection. By this way, all read and write are done in only one task, and do not require sync mechanism between connections. Below is a highly simplified pseudocode.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
TcpConn::Ready()
into one large future (maybe by usingJoinSet
?), then poll the large future, the poll result will be the ready connection, likeepoll
. But this requires writing everything in the event loop style, which is (to me) not rust's async style, and seems to be re-creating whatepoll
has already done.A more "rust async style" way is having a
conns.concurrent_in_one_task(handler_of_every_connection: async fn(c: Conn, s: StateOfNow))
API, which runs all connections in one task concurrently. And APIs to add/remove connections ofconns
.To my knowledge, it is not that simple as the pseudocode,
send()
andrecv()
system calls may send/recv only part of the buffer, and the caller should send/recv the remaining part when connection is ready again, so some additional states are required.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.
All reactions