ios - Synchronization of multiple tasks on single thread -


how can prevent block of code repeatedly accessed same thread?

suppose, have next code:

func sendanalytics() {     // synchronous work      asynctask() { _ in         completion()     } } 

i want prevent any thread accessing "// synchronous work", before completion called.

objc_sync_enter(self) objc_sync_exit(self) 

seem prevent accessing code multiple threads , don't save me accessing code single thread. there way correctly, without using custom solutions?

my repeatedly accessing, mean calling sendanalytics 1 thread multiple times. suppose, have for, this:

for in 0...10 {     sendanalytics() } 

every next call won't waiting completion inside sendanalytics called (obvious). there way make next calls wait, before completion fires? or whole way of thinking wrong , have solve problem higher, @ body?

you can use dispatchsemaphore ensure 1 call completes before next can start

let semaphore = dispatchsemaphore(value:1)  func sendanalytics() {     self.semaphore.wait()     // synchronous work      asynctask() { _ in         completion()         self.semaphore.signal()     } } 

the second call sendanalytics block until first asynctask complete. should careful not block main queue cause app become non-responsive. safer dispatch sendanalytics call onto own serial dispatch queue eliminate risk:

let semaphore = dispatchsemaphore(value:1) let analyticsqueue = dispatchqueue(label:"analyticsqueue")  func sendanalytics() {     analyticsqueue.async {         self.semaphore.wait()         // synchronous work          asynctask() { _ in             completion()             self.semaphore.signal()         }      } } 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -