Is there any way of locking an object in Swift like in C#

前端 未结 2 1936
北荒
北荒 2020-12-31 07:32

I have the following code:

func foo() {
    var sum = 0
    var pendingElements = 10

    for i in 0 ..< 10 {
        proccessElementAsync(i) { value in
          


        
相关标签:
2条回答
  • 2020-12-31 08:03

    Hope this will help you.

    func lock(obj: AnyObject, blk:() -> ()) {
        objc_sync_enter(obj)
        blk()
        objc_sync_exit(obj)
    }
    
    var pendingElements = 10
    
    func foo() {
        var sum = 0
        var pendingElements = 10
    
        for i in 0 ..< 10 {
            proccessElementAsync(i) { value in
    
                lock(pendingElements) {
                    sum += value
                    pendingElements--
    
                    if pendingElements == 0 {
                        println(sum)
                    }
                }
    
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-31 08:06

    There is no native locking tools, but there are workarounds like explained in this SO question:

    What is the Swift equivalent to Objective-C's "@synchronized"?

    Using one of the answers, you can create a function:

        func synchronize(lockObj: AnyObject!, closure: ()->()){
            objc_sync_enter(lockObj)
            closure()
            objc_sync_exit(lockObj)
        }
    

    and then:

         func foo() {
            var sum = 0
            var pendingElements = 10
    
            for i in 0 ..< 10 {
                processElementAsync(i) { value in
    
                    synchronize(pendingElements) {
                        sum += value
                        pendingElements--
    
                        if pendingElements == 0 {
                            println(sum)
                        }
                    }
    
                }
            }
        }
    
    0 讨论(0)
提交回复
热议问题