Space Vatican

Ramblings of a curious coder

Confused by sync.rb ?

I needed a reader/writer lock the other day and followed the trail to ruby’s Sync class (why this gets to call itself Sync/Synchronizer as opposed to all the other synchronisation primitives is beyond me). The documentation isn’t exactly enlightening either. I’m sure there’s all sorts of clever stuff to do with upgrading a lock you already hold and other stuff like that, but if you’re just interested in the boring case all you need is

1
2
3
4
5
6
7
8
9
  lock = Sync.new

  lock.synchronize(Sync::EX) do
    #do something that requires a writer (exclusive) lock
  end

  lock.synchronize(Sync::SH) do
    #do something that requires a reader (shared) lock
  end