-
Hello, I'm making a TCP server and I'd like all clients to be handled on the same thread. Well, actually it's a bit more complex, I'd like to group them in a certain way and have each group handled by one single task (because of the way they will access shared resources, it's a lot simpler like this and doesn't require locking Essentially, a TCP server corresponds to:
As far as I know, tokio tasks may run on different threads, hence
I've read the docs of the Any ideas? Thanks in advance. How I fixed it let server = TcpListener::bind(addr).await?;
let mut handlers = FuturesUnordered::new();
loop {
tokio::select! {
biased; // No need to use a PRNG here, we start by trying to accept, then poll the handlers
res = server.accept() => {
let (tcp_stream, _socket_addr) = res?;
handlers.push(handle_client(tcp_stream));
}
_ = handlers.next() => { } // Poll the handlers
};
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The I recommend that you use a single-threaded runtime and use |
Beta Was this translation helpful? Give feedback.
The
JoinSet
type works by spawning actual tasks, so if you are using a multi-threaded runtime, this means that the tasks can end up on different threads. One option you could go for is theFuturesUnordered
utility, which can let you run them inside a single task, however running many things inside a single task is somewhat inefficient. It's better to spawn them as separate tasks.I recommend that you use a single-threaded runtime and use
tokio::spawn
(or aJoinSet
) to spawn them.