Skip to content

Instantly share code, notes, and snippets.

@yimajo
Created June 19, 2022 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yimajo/104a13e3e063a9c8773eb9eac44eeb73 to your computer and use it in GitHub Desktop.
Save yimajo/104a13e3e063a9c8773eb9eac44eeb73 to your computer and use it in GitHub Desktop.
DispatchQueueをlabelで毎回初期化しても同じqueueが作られるわけではなくデータ競合を起こす
import Foundation
var count = 0
// 結果を保持させてすでに重複しているかを確認
var set = Set<Int>()
for item in 0..<10000 {
let queue = DispatchQueue(label: "fuga")
// データ競合以前にそもそもここでエラーになることもある。 error: Execution was interrupted.
// The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
queue.async {
count += 1
print(count, item) // データ競合が起こるとcountはmaxまでたどり着かない
if set.contains(count) {
print("同じのあるよ!", count)
} else {
set.insert(count)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment