Skip to content

Instantly share code, notes, and snippets.

@reu
Created June 14, 2012 14:24
Show Gist options
  • Save reu/2930674 to your computer and use it in GitHub Desktop.
Save reu/2930674 to your computer and use it in GitHub Desktop.
Race
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}"
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