, apeiros asQuirreL, , .
, .
1:
-, JS, :
setTimeout( function() {
console.log("world");
}, 0);
console.log("hello");
Ruby:
Branch.new do
branch { puts "world!" }
print "Hello, "
end
, , . - Branch.new { ... }.
2:
, , .
JS , Ruby:
var
results = [],
rounds = 5;
for (var i = 1; i <= rounds; i++) {
console.log("Starting thread #" + i + ".");
(function(local_i) {
setTimeout( function() {
results.push(local_i);
console.log("Thread #" + local_i + " has finished.");
if (results.length === rounds)
console.log("All " + rounds + " threads have completed! Bye!");
}, 0);
})(i);
}
console.log("All threads started!");
:
Starting thread #1.
Starting thread #2.
Starting thread #3.
Starting thread #4.
Starting thread #5.
All threads started!
Thread #5 has finished.
Thread #4 has finished.
Thread #3 has finished.
Thread #2 has finished.
Thread #1 has finished.
All 5 threads have completed! Bye!
, .
, results . JS , Ruby .
Ruby :
Branch.new 1 do
results = []
rounds = 5
1.upto(rounds) do |item|
puts "Starting thread ##{item}."
branch do |mutexes|
sleep (6.0 - item) / 10
mutexes[:array_and_output].synchronize do
puts "Thread ##{item} has finished!"
results.push item
if results.size == rounds
puts "All #{rounds} threads have completed! Bye!"
end
end
end
end
puts "All threads started."
end
puts "All threads finished!"
, , , .
3:
setTimeout, .
JS
setTimeout(function(){ console.log('Foo'); }, 2000);
branch(2) { puts 'Foo' }
4:
JS , script . /.
Ruby , Branch . Branch.new{}, . , , Branch .
Branch.new do
branch { sleep 10 }
branch { sleep 5 }
puts "All threads started!"
end
puts "All threads finished!"
Branch.new{} .
class Branch
def initialize(mutexes = 0, &block)
@threads = []
@mutexes = Hash.new { |hash, key| hash[key] = Mutex.new }
instance_eval &block
@threads.each { |thr| thr.join }
end
def branch(delay = false, &block)
@threads << Thread.new do
sleep delay if delay.is_a? Numeric
block.call @mutexes
end
end
end