swift Grand Central Dispatch(GCD)发送信号量示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift Grand Central Dispatch(GCD)发送信号量示例相关的知识,希望对你有一定的参考价值。

private func example1() {
    let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    for i in 0..<10 {
        dispatch_async(queue) {
            NSLog("Start: \(i)")
            sleep(3)
            NSLog("End: \(i)")
        }
    }
}

private func semaphoreExample1() {
    let semaphore = dispatch_semaphore_create(2)
    let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    for i in 0..<10 {
        dispatch_async(queue) {
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
            NSLog("Start: \(i)")
            sleep(3)
            NSLog("End: \(i)")
            dispatch_semaphore_signal(semaphore)
        }
    }
}

private func semaphoreExample2() {
    let semaphore = dispatch_semaphore_create(0)
    let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    dispatch_async(queue) {
        NSLog("Running async task...")
        sleep(3)
        NSLog("Async task completed")
        dispatch_semaphore_signal(semaphore)
    }
    NSLog("Waiting async task...")
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
    NSLog("Continue!")
}

private func semaphoreExample3() {
    let semaphore = dispatch_semaphore_create(0)
    let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    let n = 9
    for i in 0..<n {
        dispatch_async(queue) {
            NSLog("\(i): Running async task...")
            sleep(3)
            NSLog("\(i): Async task completed")
            dispatch_semaphore_signal(semaphore)
        }
    }
    NSLog("Waiting async task...")
    for i in 0..<n {
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
        NSLog("\(i + 1)/\(n) completed")
    }
    NSLog("Continue!")
}

private func semaphoreExample4() {
    let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    let group = dispatch_group_create()
    let n = 9
    for i in 0..<n {
        dispatch_group_async(group, queue) {
            NSLog("\(i): Running async task...")
            sleep(3)
            NSLog("\(i): Async task completed")
        }
    }
    NSLog("Waiting async task...")
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
    NSLog("Continue!")
}

以上是关于swift Grand Central Dispatch(GCD)发送信号量示例的主要内容,如果未能解决你的问题,请参考以下文章

Grand Central Dispatch(GCD)

NSOperation 与 Grand Central Dispatch

暂停和恢复 Grand Central Dispatch 线程

使用 Grand Central Dispatch 进行文件监控

核心数据和线程/ Grand Central Dispatch

Grand Central Dispatch 用于复杂流程?