Last active
February 15, 2018 20:18
-
-
Save robacarp/b7e9d7c5b883a3ec18a9 to your computer and use it in GitHub Desktop.
Testing ruby mutexs across threads and forks
This file contains hidden or 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
# Deep Thought is a computer that was created by the pan-dimensional, | |
# hyper-intelligent species of beings (whose three-dimensional | |
# protrusions into our universe are ordinary white mice) to come up | |
# with the Answer to The Ultimate Question of Life, the Universe, | |
# and Everything. Deep Thought is the size of a small city. | |
class Worker | |
MUTEX = Mutex.new | |
@@mutex = Mutex.new | |
def initialize name: 0, magnitude: 1 | |
@name = name | |
@magnitude = magnitude | |
@my_mutex = Mutex.new | |
end | |
def work | |
mutex = MUTEX | |
mutex = @my_mutex | |
mutex = @@mutex | |
while true do | |
# puts "\033[33m #{@name} is attempting to fetch lock \033[0m" | |
mutex.synchronize do | |
sleep_for = (rand() * @magnitude) + 1 | |
puts "#{Time.now.to_i} \033[35m#{@name} has mutex ##{mutex.object_id} and is sleeping for #{sleep_for}\033[0m" | |
sleep sleep_for | |
end | |
end | |
end | |
end | |
class ThreadedManager | |
def initialize | |
(1..2).map do |n| | |
puts "booting thread #{n}" | |
Thread.new do | |
Worker.new(name: n, magnitude: (n+1)).work | |
end | |
end.map(&:join) | |
end | |
end | |
class ForkedManager | |
def initialize | |
@color = '' | |
@name = 'not-yet-forked' | |
identify | |
must_wait = false | |
@color = "\033[33m" | |
2.times do |n| | |
if Process.fork | |
color = "\033[35m" | |
@name = 'not fork' | |
identify | |
must_wait = true | |
else | |
@name = "fork #{n}" | |
identify | |
must_wait = false | |
Worker.new(name: @name, magnitude: (n + 1)).work | |
end | |
end | |
if must_wait | |
Process.wait | |
end | |
end | |
def identify | |
puts "#{@color} #{@name} pid: #{Process.pid} ppid: #{Process.ppid}\033[0m" | |
end | |
end | |
if ARGV[0] == '--thread' | |
ThreadedManager.new | |
end | |
if ARGV[0] == '--fork' | |
ForkedManager.new | |
end | |
puts 'exiting' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment