:wq - blog » gem http://writequit.org/blog Tu fui, ego eris Mon, 22 Dec 2014 14:54:59 +0000 en-US hourly 1 http://wordpress.org/?v=4.1.5 Forkify 0.0.1 Ruby gem released, threadify with processes http://writequit.org/blog/2009/06/24/forkify-0-0-1-ruby-gem-released-threadify/ http://writequit.org/blog/2009/06/24/forkify-0-0-1-ruby-gem-released-threadify/#comments Wed, 24 Jun 2009 19:02:39 +0000 http://writequit.org/blog/?p=300 I’m happy to announce the release of another tiny Ruby gem, Forkify.

Forkify is basically Ara Howard’s Threadify (minus a few features), but instead of using threads, it uses fork to create multiple processes to perform the operations on an Enumerable type. It was born out of the desire to have the forkoff gem work on Ruby 1.9.1 (which it isn’t currently).

You can get Forkify using RubyGems:

sudo gem install forkify

Using it is super-simple also:

require 'forkify'
require 'pp' # optional, just for this example
r = [1, 2, 3].forkify { |n| n*2 }
pp r

=> [2, 4, 6]

Another example demonstrating the time-saving feature of using forks:

[3:hinmanm@Xanadu:~]% time ruby -rforkify -e “5.times.forkify { |n| sleep(1) }”
ruby -rforkify -e “5.times.forkify { |n| sleep(1) }”  0.02s user 0.03s system 5% cpu 1.030 total

[3:hinmanm@Xanadu:~]% time ruby -r forkify -e "5.times.forkify { |n| sleep(1) }"
ruby -r forkify -e "5.times.forkify { |n| sleep(1) }"  0.02s user 0.03s system 5% cpu 1.030 total

You can specify the maximum number of processes to spawn with an argument to forkify, the default is 5:

[1, 2, 3, 4, 5, 6].forkify(3) { |n| n**2 } # This will spawn 3 processes at a time to process the 6 items

Here you can see sleeping for 5 seconds 5 times only takes slightly longer than 1 second (instead of over 5 if you hadn’t forkified it)

Forkify is available as a gem via rubygems, or you can check out the code here: http://github.com/dakrone/forkify/. It’s still beta-quality, so please let me know if you run into any issues with it.

P.S. 100th post, woo!

]]>
http://writequit.org/blog/2009/06/24/forkify-0-0-1-ruby-gem-released-threadify/feed/ 1