Keep ref to MutexGuard in struct


I have a struct like

pub struct ElementBuffer {
    send : Arc<Mutex<spmc::Sender<ElementStreamFormat>>>,
    recv : spmc::Receiver<ElementStreamFormat>,
    guard : MutexGuard<spmc::Sender<ElementStreamFormat>>

I want the guard in the struct so I can have a unlock method and a send method operating on the struct. This is to perform some kind of rate limiting.

MutexGuard expects a lifetime parameter. How can I specify that Mutexguard lasts as lond as the send field of this stuct ?


You can't - that would create a "self-referential" struct, which is disallowed.

Can you instead pass the MutexGuard along with the work that it's protecting? Once that work is done, the guard can be dropped to release the lock. Is there a reason you want the guard to be in the struct itself?

Also, since you're using channels, you can use a SyncSender to allow backpressure and thus rate limiting (at least if receiver can't keep up). At its extreme, a SyncSender/Receiver pair with a buffer of size 0 turns this into a synchronous transfer channel - sender blocks until receiver picks it up.


Thanks. I could just pass the MutexGuard I was thinking keeping the guard would make using the api nicer but it's not a great issue.

The SyncSender just sends data eventually to a websocket. At the moment the data through this socket continues to run many tens of minutes after my actual algorithm completes. The websocket data is only there for a rough debug indication so I just want to disregard information rather than get the sender to block.


So you're saying you just need to know whether a send is in progress, and if it is, ignore any subsequent send operations?

Maybe that would be enough . I was just going to ignore sending if the rate was greater than say 10 calls a second.