Skip to content

Instantly share code, notes, and snippets.

@RomanTruba
Last active December 10, 2016 08:29
Show Gist options
  • Save RomanTruba/dd3ae8e43318bc2fd509cdc78830cae1 to your computer and use it in GitHub Desktop.
Save RomanTruba/dd3ae8e43318bc2fd509cdc78830cae1 to your computer and use it in GitHub Desktop.
import XCTest
final class LockingTests: XCTestCase {
func testSpinLock() {
var spinLock = OS_SPINLOCK_INIT
executeLockTest { (block) in
OSSpinLockLock(&spinLock)
block()
OSSpinLockUnlock(&spinLock)
}
}
func testDispatchSemaphore() {
let sem = dispatch_semaphore_create(1)
executeLockTest { (block) in
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER)
block()
dispatch_semaphore_signal(sem)
}
}
func testNSLock() {
let lock = NSLock()
executeLockTest { (block) in
lock.lock()
block()
lock.unlock()
}
}
func testPthreadMutex() {
var mutex = pthread_mutex_t()
pthread_mutex_init(&mutex, nil)
executeLockTest{ (block) in
pthread_mutex_lock(&mutex)
block()
pthread_mutex_unlock(&mutex)
}
pthread_mutex_destroy(&mutex);
}
func testSyncronized() {
let obj = NSObject()
executeLockTest{ (block) in
objc_sync_enter(obj)
block()
objc_sync_exit(obj)
}
}
func testQueue() {
let lockQueue = dispatch_queue_create("com.test.LockQueue", nil)
executeLockTest{ (block) in
dispatch_sync(lockQueue) {
block()
}
}
}
func disabled_testNoLock() {
executeLockTest { (block) in
block()
}
}
private func executeLockTest(performBlock:(block:() -> Void) -> Void) {
let dispatchBlockCount = 16
let iterationCountPerBlock = 100_000
// This is an example of a performance test case.
let queues = [
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)
]
var value = 0
measureBlock {
let group = dispatch_group_create()
for block in 0..<dispatchBlockCount {
dispatch_group_async(group, queues[block % queues.count], {
for _ in 0..<iterationCountPerBlock {
performBlock(block: {
value = value + 2
value = value - 1
})
}
})
}
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment