GCD - Critical Section/Mutex

Deadly 提交于 2019-12-08 02:09:38

问题


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.


回答1:


ok, here is the working example (credit goes to @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


来源:https://stackoverflow.com/questions/44525436/gcd-critical-section-mutex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!