Skip to content

Atomic locking of multiple sync::mutex::Mutex #16405

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

Closed
toroidal-code opened this issue Aug 10, 2014 · 7 comments
Closed

Atomic locking of multiple sync::mutex::Mutex #16405

toroidal-code opened this issue Aug 10, 2014 · 7 comments

Comments

@toroidal-code
Copy link

There's currently no way of locking on two or more sync::mutex::Mutex at once.

C++11 provides a std::lock vs std::mutex::lock, where the first is a variadic template that can lock multiple mutexes, and the second is a member method to lock a single mutex.

Maybe a sync::mutex::lock would work?

This might apply to the std wrapper Mutex types too.

@sfackler
Copy link
Member

Why is locking each mutex individually insufficient?

@toroidal-code
Copy link
Author

Sequentially locking can cause deadlock with two threads:

Thread 1     Thread 2
lock A       lock B
lock B       lock A

@toroidal-code
Copy link
Author

extern crate sync;
use sync::mutex::Mutex;

struct Node {
   mutex : Mutex
}
struct Link {
   to : &Node,
   from : &Node,
}

fn deadlock(link : &mut Link) {
  let to_guard = link.to.mutex.lock();
  let from_guard = link.from.mutex.lock();   // Deadlock can occur here
  drop(to_guard);
  drop(from_guard);
}

@bkoropoff
Copy link
Contributor

The simplest solution to the problem you gave is to just lock the mutexes in address order. You could write a series of functions or methods on tuples of mutexes to do this. Example for pairs: http://is.gd/aNnVl5

This of course requires the order to be followed everywhere in the code, which can be difficult to verify.

@toroidal-code
Copy link
Author

I'm working on a try-and-back-off method, based on libc++. I currently have locking for two mutexes, and am going to try generalizing it using macros tomorrow.
https://gist.github.com/toroidal-code/9c12d53a0f2d4e631cdd

@toroidal-code toroidal-code changed the title Atomic locking of multiple std::mutex::Mutex Atomic locking of multiple sync::mutex::Mutex Aug 16, 2014
@weswigham
Copy link

I feel like I've gotten close, but can't quite seem to get the macro functioning as I want it to: http://is.gd/EfLEIV

@toroidal-code
Copy link
Author

Since sync::mutex::Mutex isn't even a thing anymore, I'm going to close this issue.

bors added a commit to rust-lang-ci/rust that referenced this issue Jan 21, 2024
…lnicola

fix: Include `for` construct in convert to guarded return conditions
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

No branches or pull requests

4 participants