Asynchronous remote calls

Posted on August 16, 2006

I remember a long time ago when I was programming C++ and using CORBA/COM(+) most of the time, frameworks spent reams of code dedicated to make one simple thing possible: asynchronous remote calls. You start a remote call, then go about your business and return for a result.

I remember I spent huge amount of time trying to make this thing work. Let's see how Ruby can handle this task. I'm going to use XMLRPC framework for demonstration purposes. Let's say you want to fetch the latest post from your Typo blog and you want to do it asynchronously of course.

    require "xmlrpc/client"

    client = XMLRPC::Client.new2("http://www.yourblog.com/backend/xmlrpc")

    post = Thread.start {
      client.call_async(*%w|metaWeblog.getRecentPosts blog user pwd 1|).first
    }

    # do your stuff here
    $stdout.sync = true
    5.times do print '.'; sleep 1; end
    puts
    # done

    puts post.value['url']

In this code I rely on the fact that Thread#value method returns a result of the last statement of the thread's block and it joins on the thread if it's still running.

Not too bad for one-liner!

Post a comment
Comment





You may use Markdown in your comments, so please give your code snippets a four-space indent.