| 1 | = lock = |
| 2 | |
| 3 | Specify a code block to execute after obtaining a lock on the object of an expression. |
| 4 | |
| 5 | The code block constitutes a critical section that only one thread may execute at a time. |
| 6 | |
| 7 | This construct ensures that one thread does not enter a critical section of |
| 8 | code while another thread is in the critical section gated by the same |
| 9 | locked object. [[BR]] |
| 10 | If another thread attempts to enter a locked block, it will wait, blocking |
| 11 | until the lock on the object is released. |
| 12 | |
| 13 | == Grammar == |
| 14 | |
| 15 | {{{ |
| 16 | lock <expression> |
| 17 | <block> |
| 18 | }}} |
| 19 | |
| 20 | |
| 21 | == Platform == |
| 22 | |
| 23 | On .Net this acts the same as the [http://msdn.microsoft.com/en-us/library/c5kehkcz%28VS.80%29.aspx C# lock statement] |
| 24 | |
| 25 | |
| 26 | == Examples == |
| 27 | {{{ |
| 28 | # Critical section is to generate output through a single shared writer fm multiple threads |
| 29 | class Tester |
| 30 | var _statusWriter as Writer? |
| 31 | ... |
| 32 | cue init |
| 33 | ... |
| 34 | _statusWriter = MyWriter() |
| 35 | # gen and setup multiple threads with .runInThread as the thread code to run |
| 36 | ... |
| 37 | |
| 38 | def runInThread |
| 39 | while true |
| 40 | ... |
| 41 | lock _statusWriter |
| 42 | _statusWriter.writeLine(statusLine) |
| 43 | |
| 44 | }}} |
| 45 | |
| 46 | {{{ |
| 47 | # This is the example from the C# lock doc page converted to cobra |
| 48 | use System.Threading |
| 49 | |
| 50 | class Account |
| 51 | var _thisLock = Object() # is private |
| 52 | var balance as int |
| 53 | var r = Random() |
| 54 | |
| 55 | cue init(initial as int) is public |
| 56 | base.init |
| 57 | .balance = initial |
| 58 | |
| 59 | def withdraw(amount as int) as int |
| 60 | # This condition will never be true unless the lock statement |
| 61 | # is commented out: |
| 62 | if .balance < 0 |
| 63 | throw Exception("Negative Balance") |
| 64 | |
| 65 | # Comment out the next line to see the effect of leaving out |
| 66 | # the lock keyword: |
| 67 | lock _thisLock |
| 68 | if .balance >= amount |
| 69 | print "Balance before Withdrawal : ", .balance |
| 70 | print "Amount to Withdraw : -" , amount |
| 71 | .balance = .balance - amount |
| 72 | print "Balance after Withdrawal : ", .balance |
| 73 | return amount |
| 74 | else |
| 75 | return 0 # transaction rejected |
| 76 | |
| 77 | def doTransactions is public |
| 78 | for i in 0 : 100 |
| 79 | .withdraw(.r.next(1, 100)) |
| 80 | |
| 81 | class Test |
| 82 | def main is shared |
| 83 | threads = Thread[](10) |
| 84 | acc = Account(1000) |
| 85 | for i in 0 : 10 |
| 86 | t = Thread(ThreadStart(ref acc.doTransactions)) |
| 87 | threads[i] = t |
| 88 | for i in 0 : 10 |
| 89 | threads[i].start |
| 90 | }}} |
| 91 | |
| 92 | == Notes == |