Condition Variable
マルチスレッドプログラミングにおけるスレッド同期機構の一つ
1974年の論文に由来しているらしい
Monitors: An Operating System Structuring Concept
解決したい課題: Mutexを使ったクリティカルセクションで他のリソースを安全に待ちたい
あるスレッドAがmutexを使って排他的に動いているとする
このスレッドAがとあるリソースを使いたいが空いていないので待つことにする
mutex内の排他領域で動いている限り他のスレッドは停止状態なので永遠に停止してしまう
ある条件が成立するまでは他スレッドに処理をさせたい
何をする?
条件を満たすまでwaitしたり
例
https://docs.ruby-lang.org/ja/latest/class/Thread=3a=3aConditionVariable.html
https://ruby-doc.com/docs/ProgrammingRuby/html/tut_threads.html#UF
code:ruby
require 'thread'
mutex = Mutex.new
cv = ConditionVariable.new
a = Thread.new {
mutex.synchronize {
puts "A: I have critical section, but will wait for cv"
cv.wait(mutex)
puts "A: I have critical section again! I rule!"
}
}
puts "(Later, back at the ranch...)"
b = Thread.new {
mutex.synchronize {
puts "B: Now I am critical, but am done with cv"
cv.signal
puts "B: I am still critical, finishing up"
}
}
a.join
b.join
produces:
code:ruby
A: I have critical section, but will wait for cv
(Later, back at the ranch...)
B: Now I am critical, but am done with cv
B: I am still critical, finishing up
A: I have critical section again! I rule!
テストでConnectionTimeoutを強制的に発生させる例
https://github.com/abicky/activerecord-debug_errors/blob/613dbdf9d051e71a2bc80ee7e7da1736ddcc54d5/spec/activerecord/debug_errors/ext/connection_adapters/connection_pool_spec.rb#L23-L39