Charles Oliver Nutter
9/6/2007 4:39:00 AM
Cd Cd wrote:
> How come when I run this code, the following output goes line by line?
> Fetching: www.google.com
> Fetching: www.slashdot.org
> Fetching: www.mit.edu
> Got www.slashdot.org: Moved Permanently
> Got www.google.com: OK
> Got www.mit.edu: OK
You could probably explain this as follows:
Thread 1 goes for Google. Waiting for response is a blocking call, so it
yields.
Thread 2 goes for Slashdot. Waiting for response is a blocking call, so
it yields.
Thread 3 goes for MIT. Waiting for response is a blocking call, so it
yields.
From there the order largely depends on which response comes back first
and which thread get scheduled next. Given that Ruby uses only Green
threads that must generally reach an appropriate point to switch, this
seems perfectly logical.
I would also expect the result would remain mostly the same for those
first three lines, and mostly random for the next three lines, as long
as you run under Ruby 1.8. Other implementations that use all native
threads will be largely unpredictable for any sequence. When I tested
this code under JRuby, it produced a different sequence every time (and
required joining on the threads so they'd run to completion).
- Charlie