Created
July 2, 2018 05:13
-
-
Save alpaca-tc/afc645a1628e864826fa00fc63945191 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
class Database | |
def initialize | |
@mutex = Mutex.new | |
@value = 0 | |
end | |
def read | |
io_blocking { @value } | |
end | |
def write(value) | |
io_blocking { @value = value } | |
end | |
def synchronize | |
@mutex.synchronize { yield } | |
end | |
private | |
def io_blocking | |
sleep(0.1) | |
yield | |
end | |
end | |
module Current | |
def self.sign_in(user_id) | |
Thread.current[:user_id] = user_id | |
end | |
def self.user_id | |
Thread.current[:user_id] | |
end | |
end | |
database = Database.new | |
threads = 10.times.map do |i| | |
Thread.start do | |
Current.sign_in(i) | |
database.synchronize do | |
current_value = database.read | |
new_value = current_value + Current.user_id | |
database.write(new_value) | |
end | |
end | |
end | |
# 全てのthreadの完了を待つ | |
threads.each(&:join) | |
# 必ず45になる | |
puts database.read |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment