Last active
August 29, 2015 14:22
-
-
Save voltrevo/e03538e95e3701309aa2 to your computer and use it in GitHub Desktop.
mutex concept
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
var mutex = require('mutex') // (this doesn't exist, it's just an illustration) | |
var playerMutexes = getPlayerMutexes() // (as above) | |
var gameBoardMutexes = getGameBoardMutexes() // (as above) | |
var getPairs = function(arr) { | |
var results = [] | |
for (var i = 0; i !== arr.length; i++) { | |
for (var j = i + 1; j !== arr.length; j++) { | |
results.push([arr[i], arr[j]]) | |
} | |
} | |
return results | |
} | |
Promise.all(getPairs(playerMutexes).map(function(pair) { | |
return mutex.and([ | |
pair[0], | |
pair[1], | |
mutex.or(gameBoardMutexes) | |
]).lock().then(function(mutexHandle) { | |
var gameBoard = mutexHandle.value[2] | |
var playerA = mutexHandle.value[0] | |
var playerB = mutexHandle.value[1] | |
return gameBoard.play(playerA, playerB).then(mutexHandle.release) | |
}) | |
})).then(function() { | |
console.log('Everyone finished playing everyone else') | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment