| 35 | } |
| 36 | |
| 37 | void LightLock_Lock(LightLock* lock) |
| 38 | { |
| 39 | s32 val; |
| 40 | bool bAlreadyLocked; |
| 41 | |
| 42 | // Try to lock, or if that's not possible, increment the number of waiting threads |
| 43 | do |
| 44 | { |
| 45 | // Read the current lock state |
| 46 | val = __ldrex(lock); |
| 47 | if (val == 0) val = 1; // 0 is an invalid state - treat it as 1 (unlocked) |
| 48 | bAlreadyLocked = val < 0; |
| 49 | |
| 50 | // Calculate the desired next state of the lock |
| 51 | if (!bAlreadyLocked) |
| 52 | val = -val; // transition into locked state |
| 53 | else |
| 54 | --val; // increment the number of waiting threads (which has the sign reversed during locked state) |
| 55 | } while (__strex(lock, val)); |
| 56 | |
| 57 | // While the lock is held by a different thread: |
| 58 | while (bAlreadyLocked) |
| 59 | { |
| 60 | // Wait for the lock holder thread to wake us up |
| 61 | syncArbitrateAddress(lock, ARBITRATION_WAIT_IF_LESS_THAN, 0); |
| 62 | |
| 63 | // Try to lock again |
| 64 | do |
| 65 | { |
| 66 | // Read the current lock state |
| 67 | val = __ldrex(lock); |
| 68 | bAlreadyLocked = val < 0; |
| 69 | |
| 70 | // Calculate the desired next state of the lock |
| 71 | if (!bAlreadyLocked) |
| 72 | val = -(val-1); // decrement the number of waiting threads *and* transition into locked state |
| 73 | else |
| 74 | { |
| 75 | // Since the lock is still held, we need to cancel the atomic update and wait again |
| 76 | __clrex(); |
| 77 | break; |
| 78 | } |
| 79 | } while (__strex(lock, val)); |
| 80 | } |
| 81 | |
| 82 | __dmb(); |
| 83 | } |
| 84 | |
| 85 | int LightLock_TryLock(LightLock* lock) |
| 86 | { |
no test coverage detected