Locking (keyword)

From The Elements Wiki
Jump to: navigation, search

This is an Oxygene Language topic
 

Oxygene Language: Intro | Structured Overview | Grammar | Keywords | Functions



The locking statement provides thread synchronization for the statement or block of statements, by acquiring a mutex.

Example

locking MyObject do begin
  ...
end;

The locked keyword allows you to lock a method to ensure serial access to it, but there are times when you wish to prevent other accesses while you update an object.

Consider the following code:

class method BookList.Remove(aHash : integer);
begin
  locking fList do begin
    for lItem : BookListItem in fList do begin
      if lItem.fmhash = aHash then begin
        fList.Remove(lItem);
        exit;
      end;
    end;
  end;
end;

Here, we have a private fList holding different types of item and we do not want another thread to query the list until the remove has completed. In other words, other accesses to fList will be queued until this completes.

Caution: keep the code controlled by locking to a minimum so as to avoid a performance impact.


See Also