-[SDImageCache initWithNamespace]
performs dispatch_sync
to allocate NSFileManager
. What is the rationale or benefit of doing dispatch_async
for a one-liner here? See full code here at line 78.
// Init the disk cache
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
_diskCachePath = [paths[0] stringByAppendingPathComponent:fullNamespace];
dispatch_sync(_ioQueue, ^
{
_fileManager = NSFileManager.new;
});
I can't speak to the author's intent, but this is a common pattern as a part of achieving object synchronization as part of writing thread-safe code.
Rather than using locks to synchronize interaction with an object (see the Synchronization section of the Threading Programming Guide), one can use a serial queue (see the Eliminating Lock-Based Code section in the Migrating Away from Threads chapter of the Concurrency Programming Guide).
Glancing at the code, this would appear to be the author's intent (as it appears that all interaction with this object happens on that serial queue). Assuming this is the case, when using serial queues to facilitate synchronization as part of a broader thread-safe app design, it's prudent to dispatch all interaction with the object in question to the designated serial queue, regardless of how trivial the dispatched code looks. It might not be strictly necessary to do this in all cases, but it's good defensive programming style, IMHO.
So even though this allocation looks trivial, it may be part of a broader effort to ensure that all interaction with this object is dispatched to this _ioQueue
, thereby achieving a thread safe synchronization of the object and all the tasks it performs.
But you can always submit an issue to confirm the author's intent. You might also want to check the "blame" log to see if there are commit comments that illuminate the intent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With