0

Из документации Apple:

async: execute work: work The work item to be invoked on the queue.

barrier: Work items submitted prior to the barrier execute to completion, at which point the barrier work item executes.

Я ожидал, что барьер заблокирует второе замыкание(work item), пока не выполнится первое. Но в этом примере barrier, ничего не делает. Объясните в чем причина?

var map = Array<Int>()
let group = DispatchGroup()
let queue = DispatchQueue.global()

group.enter()
queue.async() {
    for _ in 1...10 {
        print(map)
    }
    group.leave()
}

group.enter()
queue.async(flags:.barrier) {
    for index in 1...10 {
        map.append(index)
    }
    group.leave()
}

group.notify(queue: DispatchQueue.main, execute: {
    print("end")
})

В консоли:

[]
[1]
[1]
[1]
[1]
[1, 2]
[1, 2]
[1, 2]
[1, 2]
[1, 2, 3]
end

1 ответ 1

1

Попробуйте вот так:

var map = [Int]()
let group = DispatchGroup()
let queue = DispatchQueue(label: "example", attributes: .concurrent)

group.enter()
queue.async() {
    for _ in 1...10 {
        print(map)
    }
    group.leave()
}

group.enter()
queue.async(flags:.barrier) {
    for index in 1...10 {
        map.append(index)
        print(map)
    }
    group.leave()
}

group.notify(queue: DispatchQueue.main, execute: {
    print("end")
})
5
  • Спасибо! Дело в DispatchQueue.global. Из описания: Calls to the suspend(), resume(), and dispatch_set_context(::) functions have no effect on the returned queues. Видимо дело в этом.
    – insFriZzz
    22 ноя 2019 в 13:36
  • Правда остался вопрос. Зачем Apple разрешают применять async(flags:.barrier) к глобальной очереди, если barrier все равно не отработает?
    – insFriZzz
    22 ноя 2019 в 13:53
  • Формально barrier срабатывает, но не так как ожидается. Позапускайте ваш пример, каждый раз он будет выдавать разные результаты. Чтобы он точно сработал, нужно создать очередь изоляции. 22 ноя 2019 в 17:26
  • Пример будет выдавать разный результат и без барьера. Не совсем понимаю, что означает срабатывает формально. Где написано, чтобы сработал барьер, нужно писать очередь изоляции?
    – insFriZzz
    22 ноя 2019 в 18:28
  • Use caution when using barriers in global background concurrent queues as these queues are shared resources. Using barriers in a custom serial queue is redundant as it already executes serially. Using barriers in custom concurrent queue is a great choice for handling thread safety in atomic or critical areas of code. raywenderlich.com/… 22 ноя 2019 в 20:10

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.