what is the difference between below 2 piece of code while output is same for both
print("1")
print("k")
print("2")
print("3")
print("4")
print("1")
DispatchQueue.global().sync {
print("k")
}
print("2")
print("3")
print("4")
I want to understand how sync works with global() queues.
The output may appear the same, but there is actually a difference in how the code is executed.In the first code snippet, the print statements are executed sequentially, one after another, in the order they are written.
In the second code snippet The statement
print("1")is executed first and prints "1" to the console.TheDispatchQueue.global().syncblock is encountered. The code inside this block will be executed synchronously on a global queue, which means it will run on a separate thread but will block the current thread until it completes.Inside theDispatchQueue.global().syncblock,print("k")is executed, printing "k" to the console.After thesyncblock completes, the execution continues to the next line, which isprint("2"). It prints "2" to the console. Similarly,print("3")andprint("4")are executed next, printing "3" and "4" respectively.So the output for the both code snippet will be