Good News for Threaded ObjC Code

xcode.jpg

Today I was telling a friend on chat that I like the idea of mutable objects. It's how I think about programming. I realize that immutability is all the rage with Clojure and Erlang, but it's not how my mind thinks - at least not yet. So I was saying that what I wanted was someone to implement the atomic compare/replace needed for lockless data structures in ObjC. Well... I had a few minutes while digesting the ordering of set elements in Clojure, and decided to google lockless data structures for ObjC - lo and behold, there's a podcast with Mike Ash on exactly this topic.

I haven't listened to it (yet), it's still downloading, but I'm going to listen and see if in the latest developer tools there is support for the lockless data structures. If so, what a lucky break! It would certainly make things a lot easier for me when I get to that level of coding.

[6/9] UPDATE: I found TransactionKit on the web, and it's got a partially done implementation of NSDictionary and NSMutableDictionary. His warnings are nice, but it leaves me with the impression that I shouldn't really trust this. It looks nice, but I need to do a lot more reading on it, and looking at the code before I'm convinced. The problem is that I also need an NSArray equivalent. We'll have to see when I get around to it.

As a note, the description of TransactionKit by it's author is here, and it's a pretty significant piece of code. Not at all what I had anticipated in my initial thoughts. In fact, it sounds pretty amazing, but he warns us all:

There's also almost certainly bugs here and there, so the idea of unwinding stack frames by hand and being able to almost reflexively spot pointers to stack variables, and which threads stack it refers to should be second nature to you. When things go wrong, they will go wrong in a stunningly complex way.

Also, Apple has done a reasonably good job of implementing a LIFO queue with OSAtomicEnqueue() and OSAtomicDequeue(), which are in the man pages. The man page even gives a nice example of putting it to use - the only problem is that you need to drop into C structs to hold the data so it's not likely to be used in a simple Cocoa implementation.

Additionally, Mike Ash (in the podcast) talks about how the atomic increment is about 10x slower than the simple ++i implementation, but it's far, far faster than the lock, increment and unlock. Makes sense, but again, it goes to Apple's comments on threading - make code that doesn't need to use lockless data structures and you're even better off. Good to know.