- Documentation
- Reference manual
- Packages
12.8.4 Foreign hash tables
As of SWI-Prolog 8.3.2 the foreign API provides access to the
internal thread-safe and lock-free hash tables that associate pointers
or objects that fit in a pointer such as atoms (atom_t
). An
argument against providing these functions is that they have little to
do with Prolog. The argument in favor is that it is hard to implement
efficient lock-free tables without low-level access to the underlying
Prolog threads and exporting this interface has a low cost.
The functions below can only be called if the calling thread is associated with a Prolog thread. Failure to do so causes the call to be ignored or return the failure code where applicable.
- hash_table_t PL_new_hash_table(int size, void (*free_symbol)(void *n, void *v))
- Create a new table for size key-value pairs. The table is
resized when needed. If you know the table will hold 10,000 key-value
pairs, providing a suitable initial size avoids resizing. The free_symbol
function is called whenever a key-value pair is removed from the table.
This can be
NULL
. - int PL_free_hash_table(hash_table_t table)
- Destroy the hash table. First calls PL_clear_hash_table().
- void* PL_lookup_hash_table(hash_table_t table, void *key)
- Return the value matching key or
NULL
if key does not appear in the table. - void* PL_add_hash_table(hash_table_t table, void *key, void *value, int flags)
- Add key-value to the table. The behaviour if key
is already in the table depends on flags. If
0
, this function returns the existing value without updating the table. IfPL_HT_UPDATE
the old value is replaced and the function returns the old value. IfPL_HT_NEW
, a message and backtrace are printed and the function returns NULL if key is already in the table. - void* PL_del_hash_table(hash_table_t table, void *key)
- Delete key from the table, returning the old associated value
or
NULL
- int PL_clear_hash_table(hash_table_t table)
- Delete all key-value pairs from the table. Call free_symbol for each deleted pair.
- hash_table_enum_t PL_new_hash_table_enum(hash_table_t table)
- Return a table enumerator (cursor) that can be used to enumerate all key-value pairs using PL_advance_hash_table_enum(). The enumerator must be discarded using PL_free_hash_table_enum(). It is safe for another thread to add symbols while the table is being enumerated, but undefined whether or not these new symbols are visible. If another thread deletes a key that is not yet enumerated it will not be enumerated.
- void PL_free_hash_table_enum(hash_table_enum_t e)
- Discard an enumerator object created using PL_new_hash_table_enum(). Failure to do so causes the table to use more and more memory on subsequent modifications.
- int PL_advance_hash_table_enum(hash_table_enum_t e, void **key, void **value)
- Get the next key-value pair from a cursor.