I am using GCD's "dispatch_apply", implementing a for - loop parallelism. I have "score" variable, defined outside the loop and I need it to be atomic. In objective C we used to have this @atomic keyword, but I don't see it in swift. Are all primitive type variables atomic by default? So far I haven't seen a conclusive answer for Swift 2.0.
Edit : I have decided to use GCD and dispatch_sync. Could somebody comment if my solution is thread safe?
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
let lockQueue = dispatch_queue_create("com.test.LockQueue", nil)
var bestScore = Int.min
var bestLocation: BoardLocation?
let possibleMoves = board.getPossibleMoves()
let i = 0
let count = possibleMoves?.count ?? 0
//using parralel loop
dispatch_apply(count, queue) { ( let i : size_t) in
let nextMove : BoardLocation = possibleMoves![i] as! BoardLocation
// clone the current board and make the move
let testBoard = ReversiBoard(board: self.board)
testBoard.makeMove(nextMove)
// if we can slay the opponent we do it no evaluation required
if (testBoard.gameHasFinished == true){
dispatch_sync(lockQueue) {
bestLocation = nextMove
bestScore = Int.max
}
// break
}
let scoreForMove : Int = self.alphaBetaEvaluateWithState(testBoard,depth: startDepth)
dispatch_sync(lockQueue) {
if (scoreForMove > bestScore) {
bestScore = scoreForMove
bestLocation = nextMove
}
}
}
if bestScore > Int.min {
dispatch_async(dispatch_get_main_queue(), {
self.board.makeMove(bestLocation!)
})
}
}