Skip to content

Instantly share code, notes, and snippets.

@ribrdb
Last active September 11, 2017 20:43
Show Gist options
  • Select an option

  • Save ribrdb/5363751 to your computer and use it in GitHub Desktop.

Select an option

Save ribrdb/5363751 to your computer and use it in GitHub Desktop.
Locks in mirah (not tested, sorry for any compilation errors)
class FooBar < Lockable
locked def foo; @foo; end
locked def foo=(foo:String); @foo = foo; end
def bar
a = withLock { @foo }
sb = StringBuilder.new
100.times { sb.append(a) }
sb.toString
end
end
import java.util.concurrent.locks.ReentrantLock
class Lockable
def initialize
@lock = ReentrantLock.new
end
def lock
@lock.lock
end
def unlock
@lock.unlock
end
macro def withLock(&block)
quote do
begin
`@call.target`.lock
`block.body`
ensure
`@call.target`.unlock
end
end
end
macro def self.locked(method:MethodDefinition)
result = MethodDefinition(method.clone)
result.body = quote do
begin
`@call.target`.lock
`method.body`
ensure
`@call.target`.unlock
end
end
result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment