@Synchronized is the thread mutex method in OC. Swift corresponds to objc_ sync_ Enter (self) and objc_ sync_ exit(self)。
The parameters in the method can only make self, and other parameters cannot achieve the purpose of mutual exclusion.
@objc private func remove() {
print("\(Thread.current)::\(array.count)")
//Mutex
objc_sync_enter(self)
while array.count > 0 {
array.removeLast()
print("\(Thread.current)::\(array.count)")
}
print("\(Thread.current)::\(array.count)")
objc_sync_exit(self)
}
In addition, semaphores are also easy to use, which can also achieve the purpose of mutual exclusion
dispatch_ semaphore_ T is something in GCD, dispatch_ semaphore_ T, like @ synchronized above, is written in OC, which is not written in swift. All contents are in dispatchsemaphore. When semaphore > = 0, the current thread will not be blocked. The thread blocking amount is less than 0. Wait() semaphore minus 1, signal() semaphore plus 1
Dispatchsemaphore, you can set the expiration time of the lock. And initial semaphore
class Test {
//Value > = 0 can be executed; Every wait (), semaphore - 1; Semaphore + 1 for each signal;
let semaphare = DispatchSemaphore(value: 1)
private var array: [Int] = []
init() {
for i in 0..<100 {
array.append(i)
}
}
func start() {
DispatchQueue.global().async {
self.remove()
}
DispatchQueue.global().async {
self.remove()
}
}
@objc private func remove() {
print("\(Thread.current)::\(array.count)")
//Semaphore after wait() execution - 1; Because it is initialized to 1 and 0 after subtracting one, it can continue to be executed.
//If the initial semaphore is 0 and minus one is - 1, the current thread is blocked immediately
semaphare.wait()
print("start")
while array.count > 0 {
array.removeLast()
print("\(Thread.current)::\(array.count)")
}
print("\(Thread.current)::\(array.count)")
semaphare.signal()
}
}
let t = Test()
DispatchQueue.global().async {
t.start()
}