Online Book Reader

Home Category

Cocoa Programming for Mac OS X - Aaron Hillegass [131]

By Root 899 0
variable for the NSOperationQueue:

#import

#import

@interface ScatteredAppDelegate : NSObject {

IBOutlet NSView *view;

CATextLayer *textLayer;

NSOperationQueue *processingQueue;

}

@property (assign) IBOutlet NSWindow *window;

@end

Switch to ScatteredAppDelegate.m. We’ll start by adding an init method:

- (id)init {

self = [super init];

if (self) {

processingQueue = [[NSOperationQueue alloc] init];

[processingQueue setMaxConcurrentOperationCount:4];

}

return self;

}

Now we’ll make use of the NSOperationQueue in addImagesFromFolderURL:. Add six lines. Be careful to balance the blocks’ braces and the message sends’ brackets:

- (void)addImagesFromFolderURL:(NSURL *)folderURL

{

[processingQueue addOperationWithBlock:^(void) {

NSTimeInterval t0 = [NSDate timeIntervalSinceReferenceDate];

NSFileManager *fileManager = [[NSFileManager alloc] init];

NSDirectoryEnumerator *dirEnum =

[fileManager enumeratorAtURL:folderURL

includingPropertiesForKeys:nil

options:NSDirectoryEnumerationSkipsHiddenFiles

errorHandler:nil];

for (NSURL *url in dirEnum)

{

// Skip directories:

NSNumber *isDirectory = nil;

[url getResourceValue:&isDirectory

forKey:NSURLIsDirectoryKey

error:nil];

if ([isDirectory boolValue])

continue;

[processingQueue addOperationWithBlock:^(void) {

NSLog(@"-- processing %@", [url lastPathComponent]);

NSImage *image = [[NSImage alloc]

initWithContentsOfURL:url];

if (!image)

return;

NSImage *thumbImage = [self thumbImageFromImage:image];

[[NSOperationQueue mainQueue]

addOperationWithBlock:^(void) {

[self presentImage:thumbImage];

[self setText:

[NSString stringWithFormat:@"%0.1fs",

[NSDate timeIntervalSinceReferenceDate] - t0]];

}];

}];

}

}];

}

That’s it! Run the application and marvel at the new and improved user experience. You should notice a significant speed increase as well, depending on your hardware.

Instead of explicitly creating NSOperation objects, we use NSOperationQueue’s addOperationWithBlock:, which creates an NSBlockOperation for us and adds it to the queue. Note how minimal our changes were; the general flow of the application is practically unchanged. It won’t always be this clean to add multithreading to an application, but you are seeing more of how blocks allow you to avoid a lot of boilerplate code by enabling you to reference variables that are in scope.

Thread Synchronization


We didn’t appear to worry about race conditions in our exercise. The reason is that the design of the application specifically avoided using any shared data structures from within the background thread. Work in the background threads was limited to enumerating the folder, opening images, and creating thumbnails. The only shared data in this case, the Core Animation layers, were modified from the main thread only. Multithreading is easiest when you can avoid race conditions altogether.

Not all multithreading problems will be solvable using this approach, however. Oftentimes, you will need to protect a section of code (or multiple sections of code) such that only one thread can be running it at a time. This is usually done with a mutex lock (mutually exclusive lock). Objective-C provides a simple way—the @synchronized directive—to employ a mutex lock:

- (void)addImage:(NSImage *)image

{

@synchronized (images) {

[images addObject:image];

}

}

The @synchronized directive uses a mutex that is unique to the object that is passed to it. In this case, we are locking on images, an NSMutableArray. Because NSMutableArray is not thread-safe (meaning that it has not been written to be modified from multiple threads), it is recommended to use a mutex lock when modifying one in a multithreaded environment. The use of @synchronized guarantees that, for all @synchronized directives on a certain object, only one thread will be able to execute the enclosed block at a time. So if two threads were attempting to call addImage: at the same time, the first would obtain the lock

Return Main Page Previous Page Next Page

®Online Book Reader