Can reuse a Thread for interaction multiple times?

I have a connection whit a tcp::stream and stay interaction sending data(take of a vector) whit a host, but in a moment the host close the connection, so can i send the rest of the vector like a return and then reassing to a new host and continue the iter in the vector?

I am thinking about save the threads into a vector and next do join into a iter, then the threads can reuse him self?

or i need to create a new thread for every new connection?
I don't know if is clear the idea?

I am noob in rust, thanks for all the help!

You can reuse threads, but totally not the way you plan to. You can't reuse them from the JoinHandle side.

This is usually solved by implementing a thread pool.

You create regular threads with just one callback function — that part is fixed and non-reusable. But the callback function can contain an infinite loop in which it reads messages from a channel (like crossbeam-channel). The loop will keep the thread going indefinitely. The channel will let you send messages to the thread and tell it what to do, and it can execute the work according to the message it has received.

You can also use rayon which already implements such threadpool.

Or use tokio if you mostly need to do network I/O.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.