That's not how you do things in Swift:
class Dwizzle {
private let countQueue = DispatchQueue(label: "hey debugger! I'm here!")
private var count = 0 //type inference to Int
func fizzle() {
countQueue.sync {
if count > 3 { return }
count += 1
}
}
}
See, no need for mutexes, or defers, or that lock_guard.Just simple closures you already know.
Now you want to expose the count variable to other types, always in a non-negotiable thread-safe manner?
private let countQueue = DispatchQueue(label: "hey debugger! I'm here!")
private var _count = 0
public var count : Int {
get {
return countQueue.sync {
return _count
}
}
set(newValue){
if newValue >= 3 {
self.countQueue.sync {
self.count = newValue
}
}
}
}
And maintain the rest.Now what if you want to clean up, and need to only one fizzling executing at a time in the whole process? Doesn't matter which process calls the fizzling?
class Dwizzle {
private static let countQueue = DispatchQueue(label: "hey debugger! I'm here!")
private var _count = 0
public var count : Int {
get {
return Dwizzle.countQueue.sync {
return _count
}
}
set(newValue){
if newValue >= 3 {
Dwizzle.countQueue.sync {
self.count = newValue
}
}
}
}
func fizzle() {
if count > 3 { return }
count += 1
}
}
To me, your code looks like a semaphore, let me introduce you to my over-the-knee fully-functional semaphore that can implement your Dwizzle class: class HackerNewsSemaphore {
private let queue = DispatchQueue(label: "sem queue")
private var count = 0
func up(){
queue.sync {
count += 1
if executeWhenUp && onlyExecuteWhen(count) {
execute(count)
}
}
}
func down(){
queue.sync {
count -= 1
if count > 0 && executeWhenDown && onlyExecuteWhen(count) {
execute(count)
}
}
}
var executeWhenUp : Bool
var executeWhenDown : Bool
var onlyExecuteWhen : (Int)->Bool
var execute : (Int)->Void
init(whenTrue: @escaping (Int)->Bool, whenUp: Bool, whenDown: Bool, execute: @escaping (Int)->Void) {
self.onlyExecuteWhen = whenTrue
self.executeWhenUp = whenUp
self.executeWhenDown = whenDown
self.execute = execute
}
}
//test
let dwizzle = HackerNewsSemaphore(whenTrue: { (i) -> Bool in return i <= 3},
whenUp: true,
whenDown: true,
execute: { i in print("fizzle \(i)") })
for x in 0...10 {
dwizzle.up()
}
for x in 0...10 {
dwizzle.down()
}
//output:
fizzle 1
fizzle 2
fizzle 3
fizzle 3
fizzle 2
fizzle 1