swift-stm

master

An optimistic STM written in Swift
lbrndnr/swift-stm

swift-stm

Twitter: @lbrndnr License

About

swift-stm is an optimistic and lock free software transactional memory written in Swift. It's very rudimental and really only a draft as of now. I wouldn't be using it in production code if I were you. Feel free to try it out though :)

What does it do exactly?

An STM allows you to write thread safe code by making blocks of code seem to be executed atomically. This means that the transaction is either executed in a given point in time or not at all. In reality, however, it just executes the transaction and notices potential collisions. The idea behind this is that in real life, collisions are rare and locks a bit of an overhead. This means that (technically) STMs are a lot easier to use (no deadlocks, better performance yada yada) than traditional locks. Note that this is just a draft, I can't guarantee mutex nor performance!

So how do I use it?

So instead of using Dispatch...

func transfer(from: Account, to: Account, amount: Int) -> Bool {
    var res = false
    
    queue.async {            
        let i = from.balance
        
        guard i >= amount else {
            return
        }
        
        from.balance = i - amount
       	to.balance = to.balance + amount
        
        res = true
    }
    
   return res
}

... you'd write something like this

func transfer(from: Account, to: Account, amount: Int) -> Bool {
    var res = false
    
    atomic {            
        let i = try from.balance.get()
        
        guard i >= amount else {
            return
        }
        
        try from.balance.set(i - amount)
        try to.balance.set(to.balance.get() + amount)
        
        res = true
    }
    
    return res
}

I must admit that the syntax is a bit clumsy as of now...

License

swift-stm is licensed under the MIT License.

Description

  • Swift Tools
View More Packages from this Author

Dependencies

  • None
Last updated: Thu Mar 14 2024 09:49:51 GMT-0900 (Hawaii-Aleutian Daylight Time)