Skip to content

Instantly share code, notes, and snippets.

/threads.rb Secret

Created March 24, 2016 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/d6363d5b74be0e4b24aa to your computer and use it in GitHub Desktop.
Save anonymous/d6363d5b74be0e4b24aa to your computer and use it in GitHub Desktop.
threads with static vars
#!/usr/bin/env ruby
### singleton
class Prime
@@start = 2
@@inst = nil
private_class_method :new
def initialize *args, **kwargs
kwargs.each {
|k,v|
instance_variable_set "@#{k}", v
}
end
def is_prime? val
flag = true
while ( @@start < val )
if ( val % @@start == 0 )
flag = false
break
end
@@start+=1
end
p "start is " + @@start.to_s + "\n"
flag
end
def self.get_instance params={}
if ( @@inst.nil? )
@@inst = new(params)
end
return @@inst
end
end
### instantiate
class Prime1
#@@start = 2
attr_accessor :start
def initialize *args, **kwargs
kwargs.each {
|k,v|
instance_variable_set "@#{k}", v
}
@start = 2
end
def is_prime? val
flag = true
#while ( @@start < val )
#p "start - #{@@start} - val - #{val}\n"
# if ( val % @@start == 0 )
# p "NOT "
# flag = false
# break
# end
# @@start+=1
#end
while ( @start < val )
if ( val % @start == 0 )
flag = false
break
end
@start+=1
end
flag
end
end
class MyInt < Numeric
attr_accessor :prime, :num
def initialize *args, **kwargs
super()
kwargs.each {
|k,v|
instance_variable_set "@#{k}", v
}
@prime = !args[0].nil? ? Prime1.new : Prime.get_instance()
p @prime
end
def check
self.prime.is_prime?(self.num)
end
end
## main
[ nil, 10 ].each {
|args|
pths = [*1..10].shuffle.map{
|i|
MyInt.new(args, num: i)
}.map {
|i|
Thread.new {
p i.num.to_s + ( i.check ? " is prime " : " is not prime" )
sleep 1
}
}
pths.map(&:join)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment