In this post I will be discussing all about dispatch_once(), why to use it?, when to use it?, what exactly it does? and what is happening under the hood?
dispatch_once() behaves as it is specified by it's name, whatever it does it is once and only once. And that's what makes it very interesting API of all in GCD. It's syntactical form in implemented below, it takes two argument, first is flag that takes care of the once thing and second is the task that you want to perform only once.
static var flag: dispatch_once_t = 0
dispatch_once(&static.flag) {
//perform some task here.
}
It is a very best and suitable API for lazily initializing shared state of any type kind of dictionary, array or anything. Also it is much faster API than locks which do same thing.
Now a million dollar thing this API is kind of a swordsman without it's sword in Single-threaded environment and can be replace by simple if-else block. We use it and Apple documentation recommends it to use in multi-threaded environment because of it's ability of being Thread-Safe, means if multiple threads are executing same shared code then it will perform a kind of lock on block/task thread is executing and won't leave until thread unlock it, meanwhile all other threads have to wail for that lock to relinquished.
dispatch_once() behaves as it is specified by it's name, whatever it does it is once and only once. And that's what makes it very interesting API of all in GCD. It's syntactical form in implemented below, it takes two argument, first is flag that takes care of the once thing and second is the task that you want to perform only once.
static var flag: dispatch_once_t = 0
dispatch_once(&static.flag) {
//perform some task here.
}
It is a very best and suitable API for lazily initializing shared state of any type kind of dictionary, array or anything. Also it is much faster API than locks which do same thing.
Now a million dollar thing this API is kind of a swordsman without it's sword in Single-threaded environment and can be replace by simple if-else block. We use it and Apple documentation recommends it to use in multi-threaded environment because of it's ability of being Thread-Safe, means if multiple threads are executing same shared code then it will perform a kind of lock on block/task thread is executing and won't leave until thread unlock it, meanwhile all other threads have to wail for that lock to relinquished.