Last active
September 11, 2017 20:43
-
-
Save ribrdb/5363751 to your computer and use it in GitHub Desktop.
Locks in mirah (not tested, sorry for any compilation errors)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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