我正在嘗試做一些後期處理如何在Swift中創建自定義完成塊
a。一旦我的一個異步功能已經完成
b。一旦我所有的異步功能都完成了。
不幸的是,我在下面的代碼中遇到了競爭條件。
func foo(stuff: AnArrayOfObjects, completed: (NSError?)->()) {
// STEP 1 OF CREATING AN OVERALL COMPLETION BLOCK: Create a dispatch group.
let loadServiceGroup: dispatch_group_t = dispatch_group_create()
// Define errors to be processed when everything is complete.
// One error per service; in this example we'll have two
let configError: NSError? = nil
let preferenceError: NSError? = nil
// some more preprocessing/variable declarations here. E.g.:
var counter = 0
// STEP 2 OF CREATING AN OVERALL COMPLETION BLOCK: Adding tasks to a dispatch group
dispatch_group_enter(loadServiceGroup)
// here i may start MULTPILE functions that are asynchronous. For example:
for i in stuff {
estore.fetchRemindersMatchingPredicate(remindersPredicate) {
// MARK: Begininning of thread
// does something here. E.g., count the elements:
counter += 1
// update the UI
dispatch_async(dispatch_get_main_queue()) {
self.sendChangedNotification() // reloads the tableview.
// WARNING: I CAN'T JUST SHOW THE counter RESULTS HERE BECAUSE IT MIGHT NOT BE DONE YET. IT IS ASYNCHRONOUS, IT MIGHT STILL BE RUNNING.
}
}
// STEP 3 OF CREATING AN OVERALL COMPLETION BLOCK: Leave dispatch group. This must be done at the end of the completion block.
dispatch_group_leave(loadServiceGroup)
// MARK: End of thread
}
// STEP 4 OF CREATING AN OVERALL COMPLETION BLOCK: Acting when the group is finished
dispatch_group_notify(loadServiceGroup, dispatch_get_main_queue(), {
// do something when asychrounous call block (above) has finished running. E.g.:
print("number of elements: \(counter)")
// Assess any errors
var overallError: NSError? = nil;
if configError != nil || preferenceError != nil {
// Either make a new error or assign one of them to the overall error.
overallError = configError ?? preferenceError
}
// Call the completed function passed to foo. This will contain additional stuff that I want executed in the end.
completed(overallError)
})
}
您應該添加你是什麼_expecting_,以及你正在遭受的實驗。有一種潛在的數據競爭:IFF語句「counter + = 1」將在不同的隊列上執行(更準確地說,沒有相同的父隊列),那麼它可能會在不同的線程上訪問,這種情況下是數據競爭。 – CouchDeveloper