Skip to content

Example for std::sync::Exclusive is dubious #146245

@kpreid

Description

@kpreid

Location (URL)

https://doc.rust-lang.org/std/sync/struct.Exclusive.html#examples

Summary

The relevant portion of the example is:

assert_sync(State {
    future: Exclusive::new(async {
        let cell = Cell::new(1);
        let cell_ref = &cell;
        other().await;
        let value = cell_ref.get();
    })
});

While it is true that this code compiles, it isn’t clear that it accomplishes anything useful, because the Exclusive-wrapped async block is Sync but not Send, and thus State too is Sync but not Send. Thus, the only benefit of using Exclusive here would be

  • if the struct State had other fields which are to be to be accessed from other threads,
  • and that access would have to occur while the future is not being polled.

These aspects are not in the example code nor discussed at all in the example’s accompanying text, and the example briefly misled me into thinking that Exclusive could be used to produce a Send future of this sort (in the context of this URLO thread, “Borrow of owned !Sync type in async function”, which contains async {} code essentially identical to this example’s). I think that this example is significantly misleading, and it should ideally be replaced with a different one that illustrates producing Send + Sync from only Send, since Sync without Send is only very narrowly useful. If that is not possible, it should be expanded to at least vaguely gesture at making use of the Sync without Send condition.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsT-libsRelevant to the library team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions