Skip to content

Instantly share code, notes, and snippets.

@filipevarjao
Created December 11, 2014 15:29
Show Gist options
  • Save filipevarjao/ecf74c2ff57cad4d91a6 to your computer and use it in GitHub Desktop.
Save filipevarjao/ecf74c2ff57cad4d91a6 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
require 'thread'
$mutex = Mutex.new
$global_count = 0
class ProcPing
def initialize(name, data, qtdMsg)
@name = name
@data = data
@qtdMsg = qtdMsg
@mailBox = Array.new
@i = -1
end
def setPeer(peer)
@peer = peer
end
def setMailBox(data)
@mailBox = data#.clone
end
def send()
@peer.setMailBox(@data)
end
def recv()
while (true)
if (@mailBox != nil) and (@mailBox.length == @data.length)
@mailBox = Array.new
break
end
end
end
def start
while (true)
send()
if(@i < @qtdMsg - 1)
recv()
else
$mutex.synchronize do
$global_count -= 1
end
break
end
@i = @i + 1
end
end
end
class ProcPong
def initialize(name, data, qtdMsg)
@name = name
@data = data
@qtdMsg = qtdMsg
@mailBox = Array.new
@i = -1
end
def setPeer(peer)
@peer = peer
end
def setMailBox(data)
@mailBox = data#.clone
end
def send()
@peer.setMailBox(@data)
end
def recv()
while (true)
if (@mailBox != nil) and (@mailBox.length == @data.length)
@mailBox = Array.new
break
end
end
end
def start
while (true)
recv()
if(@i < @qtdMsg - 1)
send()
else
$mutex.synchronize do
$global_count -= 1
end
break
end
@i = @i + 1
end
end
end
class PingPong
def initialize(tamMsg, qtdMsg, pairsN)
@tamMsg = tamMsg
@qtdMsg = qtdMsg
@pairsN = pairsN
end
def start
t = Thread.new do
array = Array.new(@tamMsg, 1)
pairs = Array.new()
count = 0
time1 = Time.now
while count < @pairsN
p1 = ProcPing.new("PING-"+count.to_s, array, @qtdMsg)
p2 = ProcPong.new("PONG-"+count.to_s, array, @qtdMsg)
pairs << [ p1, p2 ]
count +=1
end
time2 = Time.now
timeSpawn = time2 - time1
count = 0
time1 = Time.now
while count < @pairsN
(p1, p2) = pairs[count]
p2.setPeer(p1)
p1.setPeer(p2)
t1 = Thread.new { p1.start }
t2 = Thread.new { p2.start }
count +=1
end
while $global_count != 0
end
time2 = Time.now
delta = time2 - time1
line = "#{@tamMsg}\t#{@qtdMsg}\t#{@pairsN}\t#{"%.6f" % delta.to_f}"
if File.exists?("temp.txt")
file = File.open("temp.txt", "a")
file.puts(line)
file.close
else
file = File.open("temp.txt", "w")
file.puts(line)
file.close
end
end
t.join
end
end
if __FILE__ == $0
tamMsg = ARGV[0].to_i
qtdMsg = ARGV[1].to_i
pairsN = ARGV[2].to_i
pingPing = PingPong.new(tamMsg, qtdMsg, pairsN)
$global_count = pairsN*2
pingPing.start
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment