Created
June 14, 2012 14:24
-
-
Save reu/2930674 to your computer and use it in GitHub Desktop.
Race
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
require "thread" | |
class Account | |
attr_reader :amount | |
def initialize(amount) | |
@amount = amount | |
end | |
def debit(amount) | |
@amount -= amount | |
end | |
def credit(amount) | |
@amount += amount | |
end | |
end | |
transactions = 100_000 | |
quantity = 1 | |
thread_count = 10 | |
total = transactions * quantity * thread_count | |
account1 = Account.new(total) | |
account2 = Account.new(0) | |
thread_count.times.map do | |
Thread.new do | |
transactions.times do | |
account1.debit quantity | |
account2.credit quantity | |
end | |
end | |
end.each(&:join) | |
puts "account1: #{account1.amount}" | |
puts "account2: #{account2.amount}" |
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
require "thread" | |
class Account | |
attr_reader :amount | |
def initialize(initial_amount) | |
@amount = initial_amount | |
end | |
def debit(amount) | |
@amount -= amount | |
end | |
def credit(amount) | |
@amount += amount | |
end | |
end | |
account = Account.new(0) | |
transactions = 100_000 | |
quantity = 1 | |
thread_count = 10 | |
total = transactions * quantity * thread_count | |
thread_count.times.map do | |
Thread.new do | |
transactions.times do | |
account.credit quantity | |
end | |
end | |
end.each(&:join) | |
puts "Quanto tem #{account.amount}" | |
puts "Deveria ter #{total}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment