-
-
Save Terriermon/02c446d1238ad6ec1edb08b607b1bf05 to your computer and use it in GitHub Desktop.
GCD barrier in iOS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MutiReadSingleWriteObject<T> { | |
let queue = DispatchQueue(label: "com.readwrite.concurrency", attributes: .concurrent) | |
var _object:T? | |
var object: T? { | |
@available(*, unavailable) | |
get { | |
fatalError("You cannot read from this object.") | |
} | |
set { | |
queue.async(flags: .barrier) { | |
self._object = newValue | |
} | |
} | |
} | |
func getObject(_ closure: @escaping (T?) -> Void) { | |
queue.async { | |
closure(self._object) | |
} | |
} | |
} | |
func testMutiReadSingleWriteObject() { | |
let store = MutiReadSingleWriteObject<Int>() | |
let queue = DispatchQueue(label: "com.come.concurrency", attributes: .concurrent) | |
for i in 0...100 { | |
queue.async { | |
store.getObject { obj in | |
print("\(i) -- \(String(describing: obj))") | |
} | |
} | |
} | |
print("pre --- ") | |
store.object = 1 | |
print("after ---") | |
store.getObject { obj in | |
print("finish result -- \(String(describing: obj))") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment