Skip to content

unsafe impl Send + Sync are not safe #2

@cceckman

Description

@cceckman

In the Rust code, these appear:

unsafe impl Send for Display {}
unsafe impl Sync for Display {}

This is...not great. It essentially means any code entering Display will ignore thread-safety protections. For instance: two calls to set_mode might interleave, and get each other's responses.

  • Python is moving towards free-threading, so this presents an issue in Python.
  • Rust assumes that any method with a &self receiver can be used from multiple threads safely; marking something Sync without it actually being thread-safe reintroduces C-style unsafety into Rust programs that are not themselves unsafe. This breaks a contract with Rust callers.
  • C can leave a lot up to the caller, e.g. "these methods must only be called by a single thread", but this isn't documented.

It would be good to adhere to Rust's safety standards, so they can trickle back to the other APIs. Any use of unsafe should have a block explaining why it is in fact safe; in this case, adhering to the requirements that Sync and Send provide.

In this case -- I think the simplest solutions are either:

  • Putting an internal mutex in Display, around the HID device; this should allow removing the unsafe impls
  • Having a lower-level Display type without a mutex, with &mut self receivers--this would be a thread-unsafe object, so e.g. callers in C can use it without incurring the cost of the mutex-- and a ThreadSafeDisplay that wraps it in a mutex. The latter would be exported to Python.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions