Skip to content

embassy-sync: add lock_mut to blocking_mutex::Mutex #3978

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 31, 2025

Conversation

avsaase
Copy link
Contributor

@avsaase avsaase commented Mar 19, 2025

This adds a lock_mut method to blocking_mutex::Mutex in order to get direct mutable access to the protected data. This removes the need for an extra RefCell when mutable access is needed.

The method is marked unsafe because calling this method when the mutex is already locked causes UB. Other than that this implementation should be sound.

@lulf
Copy link
Member

lulf commented Mar 21, 2025

My only reservation here is that having this API we could be promoting a bad pattern of using lock_mut instead of the safer RefCell wrap, even if it's marked unsafe. At a minimum it should perhaps recommend using a RefCell in the docs to point the users towards that.

@avsaase
Copy link
Contributor Author

avsaase commented Mar 21, 2025

I'll update the doc comment to point to the safer pattern of using a RefCell. But is it really a bad pattern? This is only marked unsafe because re-entrantly locking the mutex causes UB. I can't think of another way to misuse this.

You'd need to do something like this to shoot yourself in the foot:

unsafe {
    MUTEX.lock_mut(|value| {
        MUTEX.lock_mut(|value| /* 💥 */)
    })
}	

For a blocking mutex that can't be locked across await points it seems very unlikely that someone will overlook this.

That said, I also don't like the unsafety of this. I mostly added this to avoid the boilerplate of using a RefCell in a Mutex, but that could also be solved by writing a MutexCell or something like that.

@avsaase avsaase force-pushed the blocking-mutex-lock-mut branch from 016534f to 73b4fae Compare March 21, 2025 22:15
@avsaase avsaase force-pushed the blocking-mutex-lock-mut branch from 73b4fae to 7a031ee Compare March 21, 2025 22:22
Copy link
Member

@lulf lulf left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@lulf lulf added this pull request to the merge queue Mar 31, 2025
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks Mar 31, 2025
@lulf lulf added this pull request to the merge queue Mar 31, 2025
Merged via the queue into embassy-rs:main with commit 154870b Mar 31, 2025
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants