Lock

Posted by Genie on July 12, 2020

synchronized 互斥锁

可以保证变量在作用范围内不会被其他线程改变

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Cc {
    func method(number: Int) -> Int {
        return number + 1
    }
}

func synchronized(_ anObj: AnyObject, closure: () -> Void) {
    objc_sync_enter(anObj)
    closure()
    objc_sync_exit(anObj)
}

func MyMethod(anObj: AnyObject!) {
    synchronized(anObj) {
        if anObj is Cc {
            print("is cc")
            if let a = anObj as? Cc {
                print(a.method(number: 3)) //4
            }
        }
    }
}

let cccc = Cc()
cccc.method(number: 2)
MyMethod(anObj: cccc) //3