Huawei-CPLLab / Theater

Actor model framework for Swift
Apache License 2.0
5 stars 1 forks source link

Replace lock in ActorCell with Dispatch.Semaphore #6

Open wanghc78 opened 7 years ago

wanghc78 commented 7 years ago

According to https://github.com/ReactiveCocoa/ReactiveCocoa/issues/2619, spin lock has the best performance in Swift, but it is only available in Mac and it may uses too much CPU.

The second best one is Semaphore. We can replace each ActorCell's lock with this.

ghost commented 7 years ago

I have been studying locking recently. This article is especially interesting (Mutexes and Closure Capture). You can definitely get some improvement over NSLock in some cases. The disadvantage with spin lock is that it will eat CPU if there is actually contention for the lock.

The places in which the lock is used in Theater are just during the creation/destruction of actors, so that is not typically on the hot path. A quick test does not show much change with a few different implementations of that sync method.

wanghc78 commented 7 years ago

That article is very nice. It seems our current sync() method inside ActorCell will introduce closure capture. And I found NSLock() has the synchronize method https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/NSLock.swift#L60

So a quick fix is to the NSLock's synchronize() method instead of our own sync() method.

Regarding the lock itself, right now it is not in hot patch. But I plan to add an parallel executor, which will use the lock to protect the mailbox. Then all the message deliver and execution will use the lock. At that time, we can test the Semaphore VS NSLock.