iosswiftconcurrencygrand-central-dispatchdispatch-queue

What is the difference between DispatchQueue.global().sync vs main thread


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.


Solution

  • 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.The DispatchQueue.global().sync block 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 the DispatchQueue.global().sync block, print("k") is executed, printing "k" to the console.After the sync block completes, the execution continues to the next line, which is print("2"). It prints "2" to the console. Similarly, print("3") and print("4") are executed next, printing "3" and "4" respectively.

    So the output for the both code snippet will be

    1
    k
    2
    3
    4