On Tuesday, 22 January 2013 at 10:27:58 UTC, bearophile wrote:
I have modified a little the code on RosettaCode (no changes in the logic).

monarch_dodra:

Avoids deadlock.

imagine 2 threads:
a: from 2 to 5.
b: from 5 to 2.

If both threads acquire their first lock, then you have a dead lock, and your program is basically dead.

By always locking low first, you avoid the deadlock in a rather simple but elegant way.

The Go language has four different solutions, one of them is:
http://rosettacode.org/wiki/Atomic_updates#Lock-free

[SNIP]

Bye,
bearophile

That's a good point, and I'm sure we could also have a version of D that could also do it that way. D has attomic swap operations too, AFAIK.

But I was really just answering the original question of "if you need 2 locks, why do it that way?".

Reply via email to