All Manuals > LispWorks User Guide and Reference Manual > 38 The HCL Package

NextPrevUpTopContentsIndex

gethash-ensuring

Function
Summary

A thread-safe way to get a value from a hash-table, adding a value if the key is not already present.

Package

hcl

Signature

gethash-ensuring key hash-table constructor &optional in-lock-constructor => result

Arguments

key

A Lisp object.

hash-table

A hash-table.

constructor

A function designator for a function of no arguments.

in-lock-constructor

A function designator for a function of one argument.

Values

result

A Lisp object.

Description

The function gethash-ensuring gets the value for the key key from the hash table hash-table, and if this fails constructs a new value, puts it in the table and returns it. gethash-ensuring does this in a thread-safe way, which means that all threads calling it with the same key and hash-table return the same value (as long as nothing removes it from the table).

If key is not found and constructor is non-nil, constructor is called to construct the new value. constructor is called without any lock, and can do whatever is needed. The value that constructor returns may be discarded by gethash-ensuring if, by the time it returns, there is already a matching value in hash-table (added by another thread or even inside constructor).

If in-lock-constructor is non-nil it is called with the result of constructor, or with nil if constructor is nil. in-lock-constructor is called with hash-table locked, and its return value is guaranteed to be put in the table and to be returned by gethash-ensuring. If in-lock-constructor is nil then the value that is returned by constructor, or nil, is used.

Notes
  1. If either the constructor or the in-lock-constructor is not simple, it is easier to use with-ensuring-gethash.
  2. In most situations, using constructor to do all the work (which requires minimal holding of the lock) is better than using in-lock-constructor. It means that sometimes the work that constructor did is wasted, because another thread put the value in the table, but that overhead is normally less significant than the overhead of holding the lock for longer, with the associated potential deadlocks. Use in-lock-constructor only if it is essential that the result goes into the table.
See also

ensure-hash-entry
with-ensuring-gethash
Modifying a hash table with multiprocessing


LispWorks User Guide and Reference Manual - 13 Feb 2015

NextPrevUpTopContentsIndex