num_threads
A simple short-hand for running a block of Ruby code in multiple concurrent threads.
array = Array.new(10)
10.threads do
array.pop
# interesting stuff in here
end
Huh?
Call the threads method on a Fixnum and pass it a block. It spawns that many threads, runs the block, then calls Thread#join on each thread to wait for it to finish.
How is this useful?
I was writing a lot of simple example code that spawned a few threads for Working With Ruby Threads. I got sick of writing this code:
threads = []
10.times do
threads << Thread.new do
# interesting stuff in here
end
end
threads.each(&:join)
The interesting stuff is hidden in too many layers of boilerplate. I wanted to write this:
10.threads do
# interesting stuff in here
end
These two code examples are equivalent. That's the whole point of the gem. Now the interesting stuff is easier to see with less boilerplate surrounding it.
I use this for writing example code. I imagine could also be useful in writing one-off scripts.
Installation
Install with:
$ gem install num_threads
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request