Question regarding trait bounds for some closures in gstreamer-rs

Sebastian Dröge sebastian at centricular.com
Sat Feb 19 20:01:40 UTC 2022


On Sat, 2022-02-19 at 08:16 -0700, Steven Fontaine via gstreamer-devel wrote:
> Hi, I'm in the process of building an app on top of the gstreamer
> rust bindings, and I ran into
> `gstreamer::prelude::ElementExt::connect_pad_added`.
> (https://gstreamer.pages.freedesktop.org/gstreamer-rs/stable/latest/d
> ocs/gstreamer/prelude/trait.ElementExt.html#tymethod.connect_pad_adde
> d) I noticed that the closure taken by this function and other
> similar functions is Send + Sync. I was curious about the
> justification behind marking this as Sync.

The reason for this is that the `pad-added` signal can be emitted from
any thread at any time, even concurrently.

That means that your signal handler
  a) needs to be `Send`: it must be allowed to send it to another
     thread and to use it from there
  b) needs to be `Sync`: it must be allowed to use it from multiple
     threads concurrently

> To explain my use case, I'm creating a decodebin, and within the
> decodebin, creating an appsink. The appsink's callbacks require
> access to, essentially, a `std::sync::mpsc::Sender`. (Technically
> it's a `gluttin::event_loop::EventLoopProxy, which contains `Sender`,
> but I doubt that matters.) `Sender`s are Send, but they're not Sync,
> so of course I'm wrapping the whole thing in an Arc + Mutex to make
> the compiler happy, which is fine, just a bit unfortunate.

It's a bit unfortunate that the `std::sync::mpsc::Sender` is not `Sync`
but you don't need the full `Arc<Mutex<_>>` machinery for making this
work.

You can move the sender into your callback, `clone()` it every time you
need to send something through it and use the clone for sending.

Internally the sender uses an `Arc` etc. so this is cheap, and cheaper
than putting another `Mutex` around everything.

Alternatively you could use e.g. a crossbeam channel:
  https://docs.rs/crossbeam-channel/latest/crossbeam_channel/

The sender of that implements `Send + Sync`.

-- 
Sebastian Dröge, Centricular Ltd · https://www.centricular.com


More information about the gstreamer-devel mailing list