Concurrency Coordination Reports
Mutex Try-Lock Coordination Report
Attempt a nonblocking mutex acquisition a fixed number of times and report whether the guard stayed open or blocked a later attempt.
Mutex Try-Lock Coordination Report
mutex_try_lock_coordination_report.rb
holds =
guard = Mutex.new
acquired = 0
blocked = 0
holds.times do
if guard.try_lock
acquired += 1
else
blocked += 1
end
end
guard.unlock if guard.locked?
status = if acquired == 0
"open"
elsif blocked > 0
"blocked"
else
"guarded"
end
puts "holds=#{holds}"
puts "acquired=#{acquired}"
puts "blocked=#{blocked}"
puts "status=#{status}"
holds =
guard = Mutex.new
acquired = 0
blocked = 0
holds.times do
if guard.try_lock
acquired += 1
else
blocked += 1
end
end
guard.unlock if guard.locked?
status = if acquired == 0
"open"
elsif blocked > 0
"blocked"
else
"guarded"
end
puts "holds=#{holds}"
puts "acquired=#{acquired}"
puts "blocked=#{blocked}"
puts "status=#{status}"
holds =
guard = Mutex.new
acquired = 0
blocked = 0
holds.times do
if guard.try_lock
acquired += 1
else
blocked += 1
end
end
guard.unlock if guard.locked?
status = if acquired == 0
"open"
elsif blocked > 0
"blocked"
else
"guarded"
end
puts "holds=#{holds}"
puts "acquired=#{acquired}"
puts "blocked=#{blocked}"
puts "status=#{status}"
nonblocking mutex
`Mutex#try_lock` returns `true` when it takes the lock and `false` when the guard is already held, so a second attempt that fails reports that the mutex is not reentrant and the section is busy.