lockGuard

Scope guards that temporarily acquire or release locking on the supplied object and perform the opposite operation on destruction. Compatibility is determined only by the locking methods provided by the supplied object.


Guard model


lockGuard (object -- guard)

Temporarily acquires exclusive locking and returns a guard that calls unlock on destruction.


lockSharedGuard (object -- guard)

Temporarily acquires shared locking and returns a guard that calls unlockShared on destruction.


unlockGuard (object -- guard)

Temporarily releases one exclusive lock acquisition and returns a guard that calls lock on destruction.


unlockSharedGuard (object -- guard)

Temporarily releases one shared lock acquisition and returns a guard that calls lockShared on destruction.


Examples

The example passes Ref to each DummyLock local so each guard operates on that existing local object.

Compile-time guard transitions

"lockGuard" use
"control" use

DummyLock: [{
  state: 0i32;
  lock: [1 !state];
  unlock: [0 !state];
  lockShared: [2 !state];
  unlockShared: [0 !state];
}];

{} () {} [
  a: DummyLock;
  @a lockGuard drop
  a.state printStack _:;

  b: DummyLock;
  @b lockSharedGuard drop
  b.state printStack _:;

  c: DummyLock;
  1 @c.!state
  @c unlockGuard drop
  c.state printStack _:;

  d: DummyLock;
  2 @d.!state
  @d unlockSharedGuard drop
  d.state printStack _:;
] "main" exportFunction

Expected Output During Compilation

1 Cref
2 Cref
0 Cref
0 Cref

Runtime example

"lockGuard" use
"String" use
"control" use

DummyLock: [{
  state: 0i32;
  lock: [1 !state];
  unlock: [0 !state];
  lockShared: [2 !state];
  unlockShared: [0 !state];
}];

{} Int32 {} [
  a: DummyLock;
  [
    g0: @a lockGuard;
    ("locked=" a.state LF) printList
  ] call
  ("unlocked=" a.state LF) printList

  b: DummyLock;
  1 @b.!state
  [
    g1: @b unlockGuard;
    ("released=" b.state LF) printList
  ] call
  ("relocked=" b.state LF) printList
  0
] "main" exportFunction

Expected Output

locked=1
unlocked=0
released=0
relocked=1

See also