Skip to content

Instantly share code, notes, and snippets.

@pinpox
Created August 22, 2016 12:23
Show Gist options
  • Save pinpox/974c95af9ca8a9afdf18a1895cc5d0c1 to your computer and use it in GitHub Desktop.
Save pinpox/974c95af9ca8a9afdf18a1895cc5d0c1 to your computer and use it in GitHub Desktop.
require 'thread'
class KukiBox
def initialize(num)
@kukis = num
@eatcount = {}
@m = Mutex.new
end
def take_kuki(player_id)
@m.synchronize do
return true if @kukis == 0
@kukis -=1
@eatcount[player_id] ? @eatcount[player_id] +=1 : @eatcount[player_id] =0
end
return false
end
def display_counts
p @eatcount
end
end
class Player
attr_accessor :t, :player_id
def initialize(id, thread)
@player_id = id
@t= thread
end
end
Thread.abort_on_exception = true
box = KukiBox.new(10000)
players = []
10.times { |i| players << Player.new(i , Thread.new { loop { sleep 0.001; break if box.take_kuki(i) } }) }
players.each { |p| p.t.join}
box.display_counts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment