Skip to content

Instantly share code, notes, and snippets.

@krdln
Last active August 29, 2015 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krdln/3dbb9c15bbd363c1daab to your computer and use it in GitHub Desktop.
Save krdln/3dbb9c15bbd363c1daab to your computer and use it in GitHub Desktop.
Fork-join concurrency and Send bound

In fork-join concurrency scenario (here's an example of what the interface may look like) it may happen that we would want to pass Arc<Mutex<Vec<&mut int>>> to child threads (you can imagine that instead of int there's really big structure that parent thread could access only by reference, so I think it's a pretty reasonable scenario).

So we want to wrap Vec<&mut int> in a Mutex, but that requires Send and our vector doesn't fulfill Send. So to be able to do that, we may just remove Send bound from Mutex::new. We may think that it won't introduce any unsafety, because Send or 'static bound will be checked by spawn or similar methods anyway.

But unfortunately, now we are able to pass Arc<Mutex<Rc>> too, which for sure shouldn't be legal, because of internal, non-thread safe, mutability of Rc.

So my proposed solution is to keep Send bound for Mutex::new, but decouple Send from 'static. Send would only mean "has Sync environment", and by that I mean:

If it contains &T, it's Send only if T is Sync. Type can of course opt out from Send, as usual.

(it was somewhat confusing definition, it would be better put as:)

T is Send iff it can only provide threadsafe or unique access to any U which it can access.

It could be interpreted also as (thanks, huon)

T is safe to transfer to another thread (where the thread at most lasts as long as T)

but I do want to decouple borrow-checker related things from that bound.

Current Send semantics can be achieved then by Send + 'static, and that would be used as a bound for function like spawn.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment