-
-
Save pinpox/9297c5c8ec0923bfd3bafcaa5681afc4 to your computer and use it in GitHub Desktop.
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 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