Hacker News new | ask | show | jobs
by kagakuninja 975 days ago
Mutexes aren't OK even if you only use one. They are error prone, you can forget to unlock. And of course, there is a temptation to avoid using it for efficiency reasons, because you "know" this part of the code is safe.

These days I develop servers on the JVM. We almost never think about mutexes or related things, libraries take care of that. I use Scala, and our entire data model is immutable, eliminating most race conditions. I think I had to declare something as volatile once or twice.

2 comments

> They are error prone, you can forget to unlock

That's not a problem with mutexes but with resource management in some languages. In Rust mutexes use RAII and unlock automatically - you cannot accidentally forget to unlock.

Yes but it is very easy to hold mutexes locked longer than needed because you usually don't think about when stuff is dropped in Rust, you just let it go out of scope.

I have gotten really annoying deadlocks because of this in the past.

Fair point, but in order to make a deadlock, you need a reference back to the object that holds the lock. And back references in Rust are hard to make. Most of the time if you unlock too late, you get a performance problem, not a deadlock.
> They are error prone, you can forget to unlock

That's a language issue though, rather than a mutex one. It's reasonably straightforward to fix that, as some languages (like Nim) do.