20 ms·
This is one of the areas where Zig's combination of anonymous blocks and block-based defer really pay off. To create a locked region of code is just this
by samatman 2y ago
This is one of the areas where Zig's combination of anonymous blocks and block-based defer really pay off. To create a locked region of code is just this
{
mutex.lock();
defer mutex.unlock();
// Do mutex things
}
It's possible to get this wrong still, of course, but both the anonymous scope and the use of `defer` make it easier to get things right.
Nothing can prevent poor engineering around mutex use though. I'd want a critical path for a concurrent hashmap to look like this:
{
shared_map.lock();
defer shared_map.unlock();
if (shared_map.getOrNull(foo) == null) {
shared_map.put(foo, new_val);
}
}
Where the SharedMap type has an internal mutex, and a way to check it, and all operations panic if no lock has been acquired. It could have `shared_map.lockAndGet(OrNull?)(...)`, so that the kind of problem pattern you're describing would stand out on the page, but it's still a one-liner to do an atomic get when that's all you need the critical path to perform.
I don't think these invariants are overly onerous to uphold, but one does have to understand that they're a hard requirement.
- int_19h 2y agoThis doesn't seem to add anything over and above what std::mutex in C++ or a synchronized block in Java offer?
- senderista 2y agoLess than C++. defer() is strictly inferior to RAII.