Thanh Nguyen Thanh Nguyen - 2 months ago 11
iOS Question

Dispatch_barrier_async and serial queue in GCD, what're differences between them?

I found that the working mechanism of dispatch_barrier_async is that it is only executed once all of the blocks previously added to the queue have been completed. It works similar to the serial queue.

Therefore, I do not distinguish what the differences between these two of running modes in GCD.

enter image description here

Answer

dispatch_barrier_[a]sync are meant to be used with a concurrent queue. They are also meant to be used along with calls to dispatch_[a]sync.

The common usage is the "multi-readers, one writer" pattern. You setup a concurrent queue. For "reader" blocks, you use dispatch_[a]sync. For "writer" blocks, you use dispatch_barrier_[a]sync.

This setup allows concurrent reading but only allows one writer at a time and no reading while the writing is happening.

Compare this with a serial queue where only one block at a time can ever happen.

Comments