Would have done a concurrent fetch, that Ruby1.9 added after the fiber is similar to the Golang kind, can be implemented concurrently run, but found that the efficiency has not improved, in order to confirm that fiber is not in parallel execution, so I did a test code like this.
Start with a PHP file:
<?php
$i = intval(isset($_GET[‘i‘]) ? $_GET[‘i‘] : (!empty($argv[1]) ? $argv[1] : 0));
if($i>0){
sleep(5-$i);
}
echo $i, "\n";
Then use the command line test, verify that the PHP file is not block (because there is no session lock, should not block)
time for i in {1..5}; do (curl localhost/test.php?i=$i) & if [ "$i" -eq "5" ]; then wait; fi ; done
time for i in {1..5}; do (php test.php $i) & if [ "$i" -eq "5" ]; then wait; fi ; done
Here the two ways of running time are around 4 seconds, proving that it is possible to run in parallel. Real 0m4.019s
Then executed with fiber: real 0m10.086s about 10 seconds, proving that it was all a run.
#!/usr/bin/env ruby
require ‘open-uri‘;
fib = Fiber.new do
(1..5).each do |i|
Fiber.yield open("http://localhost/test.php?i=#{i}").read
end
end
Fiber.new do
5.times do
puts fib.resume
end
end.resume
Results The test found that the concurrency could not be achieved at all, and was one in the run, run the next one run, so don't be misunderstood fiber can not be executed concurrently, and there is a more wonderful, If it is 5 Fiber.yield, but can call 6 times resume when resume, this design is really not good.
Then I found this http://stackoverflow.com/questions/3066392/can-ruby-fibers-be-concurrent on the StackOverflow.
Look at the second answer, probably said, fiber is just a control-flow structure, not for concurrency, they can not run concurrently, can only be considered a coroutine, and parallel execution is not a thing, in Ruby, the only thing that can be implemented is Thread, Then I wonder why there are so many people on the internet claiming that they can use Fiber to run concurrently? Concurrency and co-processes are different.
However, it can also be said that fiber can be implemented concurrency, this concurrency is not Parallelism, that is, can achieve so-called concurrency, but the inside is a run, and not because of the IO block automatically dispatched, You need to manually dispatch, real performance without any promotion, with only increase the complexity of the code logic, no benefit, the same is Concurrency,golang, Nodejs can be automatically dispatched in the IO blocking time, so can realize the true meaning of concurrent programming, but fiber, Just put the task one by one, and then in one waiting for them to run, completely unable to dispatch, really did not see any real use.
Like here, Http://www.infoq.com/cn/news/2007/09/ruby-1-9-fibers.
The title is: Ruby 1.9 added fiber to achieve lightweight concurrency, is directly misleading novice ah.
Ruby's fiber is not meant to be used for concurrency at all.