On Dec 11, 2009, at 7:43 PM, Keith Blount wrote:

Oops, sorry, forgot to ask: what happens if the user hits save again while the separate thread is already saving the search indexes to disk? So, there is one save which detaches a thread and starts to write the data to disk, then seconds later the user instigates another save that causes the data to be written to the same path - couldn't this corrupt the data?

Since you're passing YES for the atomically parameter of - writeToFile:atomically:, then the data won't be corrupted. Each thread will be writing to its own temporary file and then, when the write is complete, it will atomically move the file into place. However, it is up in the air as to which thread's write operation will "win". The second thread to finish will replace the file written by the first, but the order may be different than the order in which the threads were started.

You can use a lock or similar mechanism to strictly order the threads.

At some point, you might want to force the user to actually wait for background operations to complete. If saving a document entails a time-consuming process, you can't really completely hide that fact from the user. What if they hit Save over and over again in rapid succession? You don't want to detach umpteen threads, each with their own copy of the document data, each writing to their own temporary files, etc. At some point you probably want to put up a sheet saying "Saving document..." with a (possibly indeterminate) progress bar and a Cancel button.

To let the main thread know when the background save is complete, you can have the background thread do a -performSelectorOnMainThread:... call. Or, you can register an NSPort in the main thread's run loop and have the background thread message it. Etc.


By the way, in the code you proposed:

On Dec 11, 2009, at 7:37 PM, Keith Blount wrote:

// Presumably as the objects within the dictionary might
// change this should be a total copy:
NSDictionary *searchIndexesDeepCopy = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:searchIndexes]];

[NSThread detachNewThreadSelector:@selector(saveSearchIndexes:) toTarget:self withObject:searchIndexesDeepCopy];

You could actually move the unarchiving operation into the thread, too, just to increase the concurrency a bit.

Cheers,
Ken

_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to