Threading, a necessary evil

Anyone I know that really has a clue avoids multi-threading programming (except for some server applications) as there are so many gotchas. Making things thread safe sounds easy, but is extremely hard as it is quite easy to overlook an item or two I got bit by this in ReceiptWallet in 2 spots. In one case, I build thumbnails on a separate thread to keep the main thread (where the user interacts) running. The problem is that if the user does something, i.e. remove a page or change metadata, I clear the underlying document in the main thread. So the secondary thread tries to use the document that no longer exists and quickly crashes. The fix wasn’t difficult; I simply had to know when the secondary thread was running and don’t change things on the main thread until the secondary thread exited. Of course, I could never reproduce this (like many thread related bugs, it is nearly impossible to track down the cause), so figuring this out was a bit problematic.

The second thread related issue was a little easier to track down, but a bit less straightforward that I messed up. In this case, I used something like:

	[self performSelector:@selector(saveChanges) withObject:nil afterDelay:0.0];

and then proceeded to do:

	NSTask *mdImportTask = [[NSTask alloc] init];
	[mdImportTask setLaunchPath:@"/usr/bin/mdimport"];
	[mdImportTask setArguments:[NSArray arrayWithObject:path]];
	[mdImportTask launch];
	[mdImportTask waitUntilExit];
	[mdImportTask release];

The problem here is that the waitUntilExit runs the main loop until the task (which is actually a separate thread) completes. So saveChanges actually fires when the task is running. The task is in a function that can get called by saveChanges so things become messy quite fast. I had to re-work some code to fix this.

I worked on a project awhile ago that was heavily threaded and despite reassurances that the code was thread safe, it was a royal mess to track down bugs. While I use threads in a number applications I write, I write to avoid them as much as possible, except in cases where doing stuff on the main thread would make the UI unresponsive.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.