multithreading - How can these sync methods be effectively unit tested? -


based on answers this question, feel happy simplicity , ease of use of following 2 methods synchronization:

func synchronized(lock: anyobject, closure: () -> void) {     objc_sync_enter(lock)     closure()     objc_sync_exit(lock) }  func synchronized<t>(lock: anyobject, closure: () -> t) -> t {     objc_sync_enter(lock)     defer { objc_sync_exit(lock) }     return closure() } 

but sure they're doing want, want wrap these in piles of unit tests. how can write unit tests test these methods (and show synchronizing code)?

ideally, i'd these unit tests simple , clear possible. presumably, test should code that, if run outside synchronization block, give 1 set of results, give entirely separate set of results inside these synchronized blocks.

here runnable xctest verifies synchronization. if synchronize delayedaddtoarray, work, otherwise fail.

class delayedarray:nsobject {     func synchronized(lock: anyobject, closure: () -> void) {         objc_sync_enter(lock)         closure()         objc_sync_exit(lock)     }      private var array = [string]()     func delayedaddtoarray(expectation:xctestexpectation) {         synchronized(self) {             let arraycount = self.array.count             self.array.append("hi")             sleep(5)             xctassert(self.array.count == arraycount + 1)             expectation.fulfill()         }     } }  func testexample() {     let expectation = self.expectationwithdescription("desc")     let expectation2 = self.expectationwithdescription("desc2")      let delayedarray:delayedarray = delayedarray()     // example of functional test case.     let thread = nsthread(target: delayedarray, selector: "delayedaddtoarray:", object: expectation)     let secondthread = nsthread(target: delayedarray, selector: "delayedaddtoarray:", object: expectation2)     thread.start()     sleep(1)     secondthread.start()      self.waitforexpectationswithtimeout(15, handler: nil) } 

Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -