简体   繁体   English

GCD - 关键部分/互斥体

[英]GCD - Critical Section/Mutex

Can somebody answer with short example: 有人可以用简短的例子回答:

How to correctly Lock code part with condition: if this part is locked by some thread don't hold other threads just skip this part by other threads and keep going. 如何正确锁定代码部分的条件: 如果这个部分被某个线程锁定,则不保持其他线程只是跳过其他线程的这部分并继续。

ok, here is the working example (credit goes to @KenThomases ...) 好的,这是工作实例(信用转到@KenThomases ......)

import Dispatch

let semaphore = DispatchSemaphore(value: 1)
let printQueue = DispatchQueue(label: "print queue")
let group = DispatchGroup()

func longRuningTask(i: Int) {

    printQueue.async(group: group) {
        print(i,"GREEN semaphore")
    }
    usleep(1000)               // cca 1 milisecond
    printQueue.async(group: group) {
        print(i,"job done")
    }
}

func shortRuningTask(i: Int) {
    group.enter()
    guard semaphore.wait(timeout: .now() + 0.001) == .success else { // wait for cca 1 milisecond from now
        printQueue.async(group: group) {
            print(i,"RED semaphore, job not done")
        }
        group.leave()
        return
    }
    longRuningTask(i: i)
    semaphore.signal()
    group.leave()
}

printQueue.async(group: group) {
    print("running")
}

DispatchQueue.concurrentPerform(iterations: 10, execute: shortRuningTask )
group.wait()
print("all done")

and its printout 和它的打印输出

running
0 GREEN semaphore
2 RED semaphore, job not done
1 RED semaphore, job not done
3 RED semaphore, job not done
0 job done
4 GREEN semaphore
5 RED semaphore, job not done
6 RED semaphore, job not done
7 RED semaphore, job not done
4 job done
8 GREEN semaphore
9 RED semaphore, job not done
8 job done
all done
Program ended with exit code: 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM