Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Preston Lee
committed
Mar 15, 2011
1 parent
7776f18
commit 9760cc2
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
#!/usr/bin/env ruby | ||
# | ||
# A brief demonstration of the inherent problem of running multiple threads | ||
# on modern SMP (Semetric Multi-Processing, aka multi-core) machines. | ||
# | ||
# This will only native threads in Ruby 1.9, but only run on one CPU core | ||
# due to the stupid Global Interpreter Lock (GIL). Use a tool such as | ||
# Activity Monitor.app (OS X), `top' (Linux) or Task Manager (Windows) | ||
# to see the CPU usage of this script during execution. | ||
# | ||
# See: http://yehudakatz.com/2010/08/14/threads-in-ruby-enough-already/ | ||
# | ||
# Author: Preston Lee | ||
|
||
THREADS = 8 | ||
|
||
puts "Creating #{THREADS} worker threads." | ||
threads = [] | ||
(1..THREADS).each do |n| | ||
threads << Thread.new(n) do |n| | ||
# Do some long-running computation here... | ||
(1..1e7.to_i).each do |x| | ||
Math::PI * x # Math is fun.. or something! | ||
end | ||
end | ||
end | ||
|
||
puts "Waiting for workers to finish." | ||
threads.each do |t| t.join end | ||
|
||
puts "Done!" |