On Tue, May 26, 2015 at 5:29 AM, Niall Douglas
On 26 May 2015 at 3:50, Gottlob Frege wrote:
Alternatively, with a lock in each and pointers pointing to each other, you avoid deadlock by first setting (via CAS) your own state to be "I'm moving" then (if successful) setting your partner's flag to "see ya later", then (if successful) moving.
No one moves without telling the other first. You can get a live lock, but not a dead lock. The live Lock can be dealt with (particularly easily since the relationship (promise vs future) is asymmetrical - just say future always goes first, for example).
I found via empirical testing that the number of occasions when two threads both access promise and future concurrently is extremely rare. The stupidly simple method of locking both for every access I didn't find was a problem. And it's easy to test, and verify with the thread sanitiser.
Same algorithm though, right? Lock yourself, then try to lock your partner, unlock yourself if you can't lock your partner, repeat?