Skip to content

Instantly share code, notes, and snippets.

@voltrevo
Last active August 29, 2015 14:22
Show Gist options
  • Save voltrevo/e03538e95e3701309aa2 to your computer and use it in GitHub Desktop.
Save voltrevo/e03538e95e3701309aa2 to your computer and use it in GitHub Desktop.
mutex concept
'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