# sync.rb - 2 phase lock with counter
# $Date: 2009-02-20 01:41:12 +0900 (Fri, 20 Feb 2009) $
# by Keiju ISHITSUKA(keiju@ishitsuka.com)
# Sync_m#sync_locked?, locked?
# Sync_m#sync_shared?, shared?
# Sync_m#sync_exclusive?, sync_exclusive?
# Sync_m#sync_try_lock, try_lock
# Sync_m#sync_unlock, unlock
# Sync#try_lock(mode) -- mode = :EX, :SH, :UN
# Sync#lock(mode) -- mode = :EX, :SH, :UN
# Sync#synchronize(mode) {...}
fail "Thread not available for this ruby interpreter"
class Err < StandardError
fail self, sprintf(self::Message, *opt)
class UnknownLocker < Err
Message = "Thread(%s) not locked."
def UnknownLocker.Fail(th)
class LockModeFailer < Err
Message = "Unknown lock mode(%s)"
def LockModeFailer.Fail(mode)
def Sync_m.define_aliases(cl)
alias locked? sync_locked?
alias shared? sync_shared?
alias exclusive? sync_exclusive?
alias try_lock sync_try_lock
alias synchronize sync_synchronize
def Sync_m.append_features(cl)
unless cl.instance_of?(Module)
# make aliases and include the proper module.
def Sync_m.extend_object(obj)
unless (defined? locked? and
Sync_m.define_aliases(class<<self;self;end)
def sync_try_lock(mode = EX)
return unlock if mode == UN
ret = sync_try_lock_sub(mode)
until (Thread.critical = true; sync_try_lock_sub(m))
if sync_sh_locker[Thread.current]
sync_upgrade_waiting.push [Thread.current, sync_sh_locker[Thread.current]]
sync_sh_locker.delete(Thread.current)
sync_waiting.push Thread.current
Err::UnknownLocker.Fail(Thread.current)
m = sync_mode if m == EX and sync_mode == SH
Err::UnknownLocker.Fail(Thread.current)
if sync_ex_locker == Thread.current
if (self.sync_ex_count = sync_ex_count - 1) == 0
self.sync_ex_locker = nil
if sync_sh_locker.include?(Thread.current)
Err::UnknownLocker.Fail(Thread.current)
if (count = sync_sh_locker[Thread.current]).nil?
Err::UnknownLocker.Fail(Thread.current)
if (sync_sh_locker[Thread.current] = count - 1) == 0
sync_sh_locker.delete(Thread.current)
if sync_sh_locker.empty? and sync_ex_count == 0
if sync_upgrade_waiting.size > 0
for k, v in sync_upgrade_waiting
wait = sync_upgrade_waiting
self.sync_upgrade_waiting = []
def sync_synchronize(mode = EX)
attr :sync_upgrade_waiting, true
attr :sync_sh_locker, true
attr :sync_ex_locker, true
attr :sync_ex_count, true
@sync_upgrade_waiting = []
@sync_sh_locker = Hash.new
sync_sh_locker[Thread.current] = 1
count = 0 unless count = sync_sh_locker[Thread.current]
sync_sh_locker[Thread.current] = count + 1
# in EX mode, lock will upgrade to EX lock
if sync_ex_locker == Thread.current
self.sync_ex_count = sync_ex_count + 1
sync_mode == SH && sync_sh_locker.size == 1 && sync_sh_locker.include?(Thread.current)
self.sync_ex_locker = Thread.current
elsif sync_mode == EX && sync_ex_locker == Thread.current
self.sync_ex_count = sync_ex_count + 1
Err::LockModeFailer.Fail mode
#Sync_m.extend_class self