-
from what i understand, the swarm is the way to go in order to publish and listen for incoming messages. I have created a simple struct that contains a field that needs to be accessed by two threads, so I put it behind a Arc and Mutex:
The first function listen(), needs to lock on the swarm field and call select_next_some() which returns a Future that resolves when the next item in this stream is ready. Which means it keeps holding the lock on that field.
But I need to access and lock that Mutex in another method, I need to use the same field to send messages and receive messages at the same time:
Are there any ways to listen for messages and publishing them using the swarm at the same time? Or am I using a bad way to publish and listen for messages at the same time? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @revoltez, |
Beta Was this translation helpful? Give feedback.
Hi @revoltez,
examples/file-sharing.rs might be helpful here. It showcases an alternative architecture for driving and accessing a swarm in a larger application, without a Mutex.
The basic idea there is that the swarm is polled in an event-loop running in a background task, and actions are performed by sending commands via a mpsc channel to this background task. The event-loop performs actions on the swarm accordingly, and returns their result in a one-shot channel once they resolved. This allows to trigger multiple async actions in parallel from multiple threads, since each thread can simply hold one copy of the
mpsc::Sender
.Let me know if this helps. 🙂