Working with threads in RubyCocoa

Posted by Ben Jackson Thu, 14 Feb 2008 02:09:19 GMT

The short answer: don't use them. Ruby threads (at least before 1.9) are not OS native, and while there is a patch to the ruby interpreter included in Leopard's ruby to work around this issue, it's not 100%. It's all too easy for a thread to access memory after it's been garbage collected, and you, the developer, have to always remember to never call anything GUI-related from a separate thread, instead littering your code with calls to performSelectorOnMainThread:withObject:waitUntilDone anytime you need to update the user interface from a thread other than the main one.

So what's the best solution? Props to Eloy for tipping me off that it's better to rely on Cocoa's native asynchronous functions anytime you need to do something long-running like, say, detect a weblog's API. NSURLConnection and NSURLDownload are your best friends. They use native threads and are much more stable. Use them with respect and you'll be much further along on your way to a crash-free application.

One thing to note about NSURLConnection is that it encapsulates a single request only, and will not follow redirects, so make sure to check the response code in connection:didReceiveResponse.

Good luck and happy threading.


Posted in  | Tags , , , ,  | 2 comments | no trackbacks

Comments

  1. Praful said 14 days later:

    I am working on an app that has a GUI with a worker thread. I noticed that the examples provided with Leopard, eg SimpleApp, update the GUI in a thread (see AppController.rb for that project). I've done the same in my app: I write to a textview to provide information about progress. Are these applications broken?

  2. Benjamin Jackson said 14 days later:

    Broken, no. Potentially unstable, yes. The patch to the ruby interpreter takes care of a lot of loose ends, but your app (and the example) both have the potential to access memory which has been garbage collected.

    See the MacRuby project for an explanation on why Ruby's threading model does not jive with Cocoa's.

Trackbacks

Use the following link to trackback from your own site:
http://www.unfitforprint.com/trackbacks?article_id=working-with-threads-in-rubycocoa&day=14&month=02&year=2008

Comments are disabled