How do I atomically increment a variable in Swift?

后端 未结 7 745
别那么骄傲
别那么骄傲 2020-11-29 18:59

I want to be able to increment a counter atomically and I can\'t find any reference on how to do it.

Adding more information based on comments:

  • Are yo
相关标签:
7条回答
  • 2020-11-29 19:43

    I improved on the answer from @florian, by using some overloaded operators :

    import Foundation
    
    class AtomicInt {
    
        private var mutex = pthread_mutex_t()
        private var integer: Int = 0
        var value : Int {
            return integer
        }
    
    
        //MARK: - lifecycle
    
    
        init(_ value: Int = 0) {
            pthread_mutex_init(&mutex, nil)
            integer = value
        }
    
        deinit {
            pthread_mutex_destroy(&mutex)
        }
    
    
        //MARK: - Public API
    
    
        func increment() {
            pthread_mutex_lock(&mutex)
            defer {
                pthread_mutex_unlock(&mutex)
            }
            integer += 1
        }
    
        func incrementAndGet() -> Int {
            pthread_mutex_lock(&mutex)
            defer {
                pthread_mutex_unlock(&mutex)
            }
            integer += 1
            return integer
        }
    
        func decrement() {
            pthread_mutex_lock(&mutex)
            defer {
                pthread_mutex_unlock(&mutex)
            }
            integer -= 1
        }
    
        func decrementAndGet() -> Int {
            pthread_mutex_lock(&mutex)
            defer {
                pthread_mutex_unlock(&mutex)
            }
            integer -= 1
            return integer
        }
    
    
        //MARK: - overloaded operators
    
       static func > (lhs: AtomicInt, rhs: Int) -> Bool {
            return lhs.integer > rhs
        }
    
        static func < (lhs: AtomicInt, rhs: Int) -> Bool {
            return lhs.integer < rhs
        }
    
        static func == (lhs: AtomicInt, rhs: Int) -> Bool {
            return lhs.integer == rhs
        }
    
        static func > (lhs: Int, rhs: AtomicInt) -> Bool {
            return lhs > rhs.integer
        }
    
        static func < (lhs: Int, rhs: AtomicInt) -> Bool {
            return lhs < rhs.integer
        }
    
        static func == (lhs: Int, rhs: AtomicInt) -> Bool {
            return lhs == rhs.integer
        }
    
        func test() {
            let atomicInt = AtomicInt(0)
            atomicInt.increment()
            atomicInt.decrement()
            if atomicInt > 10  { print("bigger than 10") }
            if atomicInt < 10  { print("smaller than 10") }
            if atomicInt == 10 { print("its 10") }
            if 10 > atomicInt  { print("10 is bigger") }
            if 10 < atomicInt  { print("10 is smaller") }
            if 10 == atomicInt { print("its 10") }
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题