MMiroslav
MMiroslav

Reputation: 1762

How to lock/unlock variable in Swift Perfect framework

How to lock var transactions in Swift Perfect framework, to avoid inserting new transaction by some other thread, just before I remove all items in function storeTransactions():

class Foo {
    var transactions: [Transaction] = []

    func storeTransactions() {
        let transactionStogare = Storage(transactions: self.transactions)
        // <-- Some thread can append new transaction in this moment
        self.transactions = []
        // TODO: do something with transactionStogare
    }

    func appendTransaction(t: Transaction) {
        self.transactions.append(t)
    }
}

Just bear in mind that solution should work on Linux as well.

Upvotes: 1

Views: 875

Answers (1)

user9335240
user9335240

Reputation: 1799

You should:

import PerfectThread

This gives you a lot of threading utilities implemented by the framework itself (so, it is handled both on Linux and macOS)

In your case, you want a "shared data" to be read from multiple threads, but when written, it must wait for other read/write threads to finish their jobs. You would use Threading.RWLock.

You could do something like that:

class TransactionContainer {
    let lock = Threading.RWLock()
    private var _transactions: [Transactions]

    var transactions: [Transactions] {
        get {
            defer { // This is done after return
                lock.unlock()
            }
            lock.readLock() // Make a "read" lock, which permits
                            //  multiple reads, but no concurrent
                            //  writing.
            return _transactions
        }
        set(value) {
            lock.doWithWriteLock { // Do a write lock, which
                                   //   doesn't permit concurrent writing
                                   //   nor concurrent reading.
                                   // This is an easier expression than
                                   //   using defer and lock.unlock()
                                   //   but can't be used for returning
                                   //   because it is closure
                self._transactions = value
            }
        }
    }
}

Upvotes: 0

Related Questions