I tried multiple solution/answers given on stackoverflow but none of them worked for me. Some of them is as below :
https://stackoverflow.com/a/30495424/3145189
Is this safe to call wait() of DispatchSemaphore several times at one time?
https://stackoverflow.com/a/37155631/3145189
I am trying to achieve very simple thing, code block or function should execute serially, regardless of from which thread it's been called.
My Example code :
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
DispatchQueue.global().async {
self.testLog(name:"first")
}
DispatchQueue.global().async {
self.testLog(name:"second")
}
DispatchQueue.main.async {
self.testLog(name: "mainthread")
}
}
func testLog(name:String) -> Void {
for i in 1..<1000 {
print("thread test \(i) name =\(name)")
}
}
So output should be like -
first thread call
thread test 1 name =first
thread test 2 name =first
thread test 3 name =first
.
.
.
thread test 999 name =first
second thread call
thread test 1 name =second
thread test 2 name =second
.
.
.
thread test 999 name =second
main thread call
thread test 1 name =mainthread
thread test 2 name =mainthread
.
.
.
thread test 999 name =mainthread
If function is called on first thread, it should continue print log for the first thread only. Order of thread can vary I don't care means even if it's print mainthread log first then second and first doesn't matter logs should be grouped.